Protected method access

I just want to make a note of something I read here:

http://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Classes#Protected

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

It says:

“If age is private, this method will not work, because other.age is
not accessible. If “age” is protected, this will work fine, because
self and other are of same class, and can access each other’s
protected methods.”

That statement is not actually true. They won’t access each other’s
protected methods. They will access their own protected methods of the
same class.

Demonstration:

1.9.3p0 :001 > class A
1.9.3p0 :002?> protected
1.9.3p0 :003?> def method
1.9.3p0 :004?> puts “self is #{self.object_id}”
1.9.3p0 :005?> end
1.9.3p0 :006?> end

1.9.3p0 :009 > class A
1.9.3p0 :010?> def calling_method(o)
1.9.3p0 :011?> self.method
1.9.3p0 :012?> o.method
1.9.3p0 :013?> end
1.9.3p0 :014?> end
=> nil
1.9.3p0 :015 > b = A.new
=> #<A:0x007fcfe5b20900>
1.9.3p0 :016 > a.calling_method(b)
self is 70265443297880
self is 70265444304000

As you can see, b is not invoking a’s protected method. It’s invoking
its own, that was stored separately in this object, just as the
instance vars are stored separately per object. I’m sure that’s what
the book intended, but when it comes to writing, you have to be
careful to clarify for accuracy.