Ruby – Protected and Private

I keep forgetting this myself as Ruby’s way of handling Protected and Private is completely different to a lot of other programming languages. Lifted from Wikipedia here’s the basic explanation:

In Ruby, private visibility is what protected was in Java. Private methods in Ruby are accessible from children. This is a sensible design, since in Java, when method was private, it rendered it useless for children classes: making it a rule, that all methods should be “protected” by default, and never private. However, you can’t have truly private methods in Ruby; you can’t completely hide a method.

The difference between protected and private is subtle. If a method is protected, it may be called by any instance of the defining class or its subclasses. If a method is private, it may be called only within the context of the calling object—it is never possible to access another object instance’s private methods directly, even if the object is of the same class as the caller. For protected methods, they are accessible from objects of the same class (or children).

So, from within an object “a1″ (an instance of Class A), you can call private methods only for instance of “a1″ (self). And you can not call private methods of object “a2″ (that also is of class A) – they are private to a2. But you can call protected methods of object “a2″ since objects a1 and a2 are both of class A.

*name

*e-mail

web site

leave a comment