Forum: Ruby When to Use Protected vs. Private?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Thomas S. (Guest)
on 2006-01-19 23:59
Can someone clarify the difference between declaring a method Protected
vs. Private?

I thought that a private method could only be accessed within the
specific defining class.  However, it may also be called by subclasses.
So why the need for protected?

Thanks in advance!
unknown (Guest)
on 2006-01-20 00:47
(Received via mailing list)
Hi --

On Fri, 20 Jan 2006, Thomas S. wrote:

> Can someone clarify the difference between declaring a method Protected
> vs. Private?
>
> I thought that a private method could only be accessed within the
> specific defining class.  However, it may also be called by subclasses.
> So why the need for protected?

A private method can only be called with no explicit receiver.  That
means that the receiver has to be "self" -- because that's the only
time there can be no explicit receiver.  (Private methods ending in
"=" do allow an explicit receiver, because they have to so that they
won't be parsed as variable assignments.)

What protected does is to let you call a method *with* an explicit
receiver, as long as that receiver is of the same class is "self".

That means you can do things like:

   def compare_with(other)
     self.x <=> other.x
   end

even if x is protected, whereas you can't do that from the outside
(without instance_eval or some other "invasive" technique).


David

--
David A. Black
removed_email_address@domain.invalid

"Ruby for Rails", from Manning Publications, coming April 2006!
http://www.manning.com/books/black
This topic is locked and can not be replied to.