In Ruby, we can define a protected property in a class using the attr_protected
method.
Here's an example:
main.rb175 chars14 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