From: Kaye Ng Date: 2011-04-09T19:24:48+09:00 Subject: private vs. protected question 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 # (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 # (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!! -- Posted via http://www.ruby-forum.com/.