When to Use Protected vs. Private?

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!

···

--
Posted via http://www.ruby-forum.com/.

Hi --

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

···

On Fri, 20 Jan 2006, Thomas Snide wrote:

--
David A. Black
dblack@wobblini.net

"Ruby for Rails", from Manning Publications, coming April 2006!

Hi,

There is a subtle difference: While private fields are limited to a
single instance of a class, protected fields in an instance of a class
can be accessed from other instances of that class or its subclasses.

AFAIK there is no such thing as "private" and "protected" fields in Ruby.
Fields are always private. You can of course access them via
instance_variables(), instance_variable_get() and _set().

You probably meant the same as David but got the wording wrong. :slight_smile:

Yep, I meant "methods", not "fields". Dunno why I wrote "fields".

Regards,
   Marco