protected that makes a method private, but within the scope of a class rather than within a single object. : Protected « Class « Ruby






protected that makes a method private, but within the scope of a class rather than within a single object.


# you can call a protected method from the scope of the methods of any object 
# that's a member of the same class:

class Person
  def initialize(age)
    @age = age
  end

  def age
    @age
  end

  def age_difference_with(other_person)
    (self.age - other_person.age).abs
  end

  protected :age
end

fred = Person.new(34)
chris = Person.new(25)
puts chris.age_difference_with(fred)
puts chris.age

 








Related examples in the same category

1.A method marked protected can be used only by instances of the class where it was defined, or by derived classes.