add a protected property to a class in ruby

In Ruby, we can define a protected property in a class using the attr_protected method.

Here's an example:

main.rb
class Person
  attr_reader :name
  attr_protected :age

  def initialize(name, age)
    @name = name
    @age = age
  end

  def display_age
    puts "Age: #{@age}"
  end
end
175 chars
14 lines

In this example, we have defined a Person class with two properties - name and age. We have used the attr_reader method to create a getter method for the name property.

We have used the attr_protected method to create a protected property for age. Protected properties can be accessed by any instance of the same class or its subclasses, but cannot be accessed by other classes.

We have also defined a display_age method that can be used to display the age of the person. This method can access the protected age property because it is defined in the same class as the property.

gistlibby LogSnag