Arun Agrawal’s Blog

Ruby on Rails Developer

Method Visibility Public, Protected, Private

Instance methods may be publicprivate, or protected.

Methods are normally public unless they are explicitly declared to be private or protected. One exception is the initialize method, which is always implicitly private. Another exception is any “global” method declared outside of a class definition—those methods are defined as private instance methods of Object. A public method can be invoked from anywhere—there are no restrictions on its use.

A private method is internal to the implementation of a class, and it can only be called by other instance methods of the class (or, as we’ll see later, its subclasses). Private methods are implicitly invoked on self, and may not be explicitly invoked on an object. If m is a private method, then you must invoke it in functional style as m. You cannot write o.m or even self.m.

A protected method is like a private method in that it can only be invoked from within the implementation of a class or its subclasses. It differs from a private method in that it may be explicitly invoked on any instance of the class, and it is not restricted to implicit invocation on self. A protected method can be used, for example, to define an accessor that allows instances of a class to share internal state with each other, but does not allow users of the class to access that state.