Protected methods: not clear to me and highly confusing

class Person

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

def <=>(other)
    age <=> other.age
end

attr_reader :name,:age
protected :age

end

p1 = Person.new(“Fred”,21)
puts p1.age

That causes an error:
NoMethodError: protected method `age’ called for #<Person:0x2dc876c @age=31, @name=“fred”>
from (irb):41

However check this one out.
p2 = Person.new(“John”,23)
compage = (p1 <=> p2)

This one works.

My question is how come “other.age” works however “p1.age” doesn’t . I guess it has something to do with scope. Can someone put the explanation in an easy to understand

sentence.

That's how ruby works.
http://weblog.jamisbuck.org/2007/2/23/method-visibility-in-ruby

This is a ruby-talk question :slight_smile:

First off you are giving Ruby some confused signals.

attr_reader says to creat public accesor age. Then you declare age as
protected. Protected methods are not to be accessed outside the class.
Do not define age method protected.

Thanks Pratik but Jamis article didn’t elaborate much. At least not for me.

  • Neeraj

Hi --

class Person

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

   def <=>(other)
       age <=> other.age
   end

   attr_reader :name,:age
   protected :age
end

p1 = Person.new("Fred",21)
puts p1.age

That causes an error:
NoMethodError: protected method `age' called for #<Person:0x2dc876c @age=31,
@name="fred">
       from (irb):41

However check this one out.
p2 = Person.new("John",23)
compage = (p1 <=> p2)

This one works.

My question is how come "other.age" works however "p1.age" doesn't . I guess
it has something to do with scope. Can someone put the explanation in an
easy to understand sentence.

At the time you call a protected method on x, self must be an instance
of the same class (or a subclass) as x.

That is true inside <=>, where both self and other are of class
Person. But it's not true at the top level, where p1 is a Person but
self is the Object instance main (the top-level default object).

You should, as another poster suggested, have a look at the ruby-talk
list if you have Ruby-specific questions -- not because they're not
directly relevant to Rails development but because they'll fit in
better there and probably get more response overall.

David