Self ish privates in Ruby

Have you ever wondered why you can not call private methods from outside the class? and why only from methods inside the class?

Because method execution in Ruby happens in 2 steps:

  1. Find the method being called.
  2. Execute it.

To find the method, Ruby searches for the method in the ancestor chain of the object.

To execute the method, the method needs to have a receiver. A receiver is the object on which the method is called.

There are 2 kinds of receivers :

  1. Explicit receiver
  2. Implicit receiver

For example :

class Project

  def initialize(name, cost, duration)
    @name = name
    @cost = cost
    @duration = duration
  end

  def display_name
    "Project name : #{@name}"
  end

  private

  def billing
    @cost * @duration
  end
end

Explicit receiver is when you say,

p1 = Project.new("rails")    
p1.display_name

where p1 is the explicit receiver of the method display_name.

Thats all good for public methods. What about private methods?

Private methods also need receivers, but the receiver needs to be implicit.

Here is an example of an implicit receiver in play,

class Project
  def generate_bill
    puts "Self is #{self}"
    "$#{billing}"
  end
end

Here, the billing method is called with self (implicitly) as the receiver.

Implicit receiver is when method is called without an object being explicitly specified.

However, if we tried doing this,

class Project
  def generate_bill
    "$#{self.billing}"
  end
end

This would raise a NoMethodError. Because we explicitly called this method, even though on self.

Hope this clarifies.

Shoot any feedback/questions/doubts at murtuzafirst@gmail.com, and I would love to answer them!

Murtuza Kutub

Read more posts by this author.

Chennai, India

Subscribe to Murtuza's Blog

Get the latest posts delivered right to your inbox.

or subscribe via RSS with Feedly!