Ruby - Public, Protected, and Private Methods

Introduction

You may want to restrict the "visibility" of your methods.

In this way you can ensure that they cannot be called by code outside the class in which the methods occur.

Ruby provides three levels of method accessibility:

  • public
  • protected
  • private

public methods are the most accessible.

private methods are the least accessible.

All your methods are public unless you specify otherwise.

When a method is public, it is available to be used by the world outside the object in whose class it is defined.

When a method is private, it can be used only by other methods inside the object in whose class it is defined.

A protected method is visible to the methods of the current object and it is also visible to objects of the same type when the second object is within the scope of the first object.

class MyClass 
    private       
        def priv 
             puts( "private" ) 
        end 
    protected 
        def prot          
             puts( "protected" ) 
        end       
    public             
        def pub 
             puts( "public" ) 
        end 
        def useOb( anOb ) 
             anOb.pub 
             anOb.prot 
             anOb.priv 
        end    
end    

Here, the code declared three methods, one for each level of accessibility.

These levels are set by putting private, protected, or public prior to one or more methods.

The specified accessibility level remains in force for all subsequent methods until some other access level is specified.

The class has a public method, useOb, which takes a MyOb object as an argument and calls the three methods pub, prot, and priv of that object.

First, I'll create two instances of the class:

myob = MyClass.new 
myob2 = MyClass.new 

myob.pub         # This works! Prints out "public" 
myob.prot        # This doesn't work! 
myob.priv        # This doesn't work!
myob.useOb( myob2 ) 

Here is what will happen:

def useOb( anOb ) 
   anOb.pub     # OK to call
   anOb.prot    # protected method can be called 
   anOb.priv    # calling a private method results in an error 
end     

Related Topics