From a book I’m reading:
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
results in:
9
:20: protected method ‘age’ called for #<Person:0x1e5f28 @age=25>
(NoMethodError)
The first ‘puts’ line printed ‘9’ on the screen, while the second
resulted
in error. This is because, like ‘private’, I cannot use a specific
receiver to call a protected method, correct?
Now I’m going to replace ‘protected’ with ‘private’ (and omit the last
line (puts chris.age) ). This would result in:
H:/Ruby/Practice/six.rb:9:in age_difference_with': private method
age’
called for
#<Person:0x19ccf68 @age=25> (NoMethodError)from
H:/Ruby/Practice/six.rb:16:in `’
Explanation from the book:
" if
age were made private, the preceding example would fail because
other_person.age would
be invalid. That’s because private makes methods accessible only by
methods of a specific
object."
From the statement, “…because private makes methods accessible only by
methods of a specific
object.”, I’m assuming that it also means ‘accessible only by methods of
a single and CURRENT object’, and that current object is ‘chris’, not
‘fred’, and that is why it resulted in error.
Am I wrong??
Help please! Thank you!!