Matt's Blog

Ruby Private Methods vs. Protected Methods

by Matt Hodan on August 08, 2010

Let’s talk Ruby access control basics… In Ruby, the primary difference between a private and a protected method is that a private method cannot be called with an explicit receiver, while a protected method can.

An explicit receiver is the object that is receiving a message. In the following example, we have a receiver (“parent”) and a method (“get_name”). The “parent” object is receiving the instruction to perform the “get_name” method.

parent.get_name

The following code illustrates that a private method cannot be called by an explicit receiver:

class Parent
  private
  def name
    'Mommy'
  end
end

class Child < Parent
  def get_parent_name
    # Implicit receiver
    puts name

    # Explicit receiver
    puts self.name rescue puts 'NoMethodError'

    # Explicit receiver
    puts Parent.new.name rescue puts 'NoMethodError'
  end
end

Child.new.get_parent_name
# => Mommy
# => NoMethodError
# => NoMethodError

We’ve created a “Parent” class and a “Child” class that is a sub-class of Parent. Parent has a private method “name” that returns the value “Mommy”. When we call “Child.new.get_parent_name” on line 18, we see the output produced by lines 12-14. Only when the Parent’s method “name” is called with an implicit receiver do we get a return value.

What does this mean? This means that private methods can only be called within the context of the current object (since any context outside of the current object would require an explicit receiver). I.e. one object cannot access another object’s private methods.

Extra credit: Try changing “private” to “protected” in the above gist and take a look at the output.


comments powered by Disqus

Recent Articles