Ruby method lookup


In ruby, which method gets executed when we extend or include it to the class. Which method has more precedence, singleton method or instance method…? See the example below

module Developer
  def name
    puts "Hi. This is Developer"
  end
end

module Analyst
  def name
    puts "Hi. This is Analyst"
  end
end

class Employee
  include Developer
  # included into the class

  # instance method of the class
  def name
    puts "Hi. This is Employee"
  end
end

e = Employee.new
e.extend(Analyst)

# extended into the class

e.name

Hi. This is Analyst

Look why the method call went to Analyst module, rather than the other two modules, Developer and Employee instance method. This means that extend has more precedence over include and instance method. Let’s see how ruby handles precedence over singleton method, superclass method and instance method.

Ruby method precedence

Ruby has various ways to define a method in a class and this makes ruby lookup path quite complicated. But it’s quite easy to implement and understand. A method in ruby can be defined in following means:

Defining method to the class.
Inheriting method from superclass.
Including method to the module.
Prepending method to the module.
Extending method to the module.
Adding method to the singleton class.

Let us find lookup path through the small piece of code below.

module Reviewer
  def name
    puts "Hi. This is Reviewer"
    super rescue nil
  end
end


module Manager
  def name
    puts "Hi. This is Manager"
    super rescue nil
  end
end

module Analyst
  def name
    puts "Hi. This is Analyst"
    super rescue nil
  end
end

class Employee

  # inherited method to class Employee
  def name
    puts "Hi. This is Employee "
    super rescue nil
  end
end

class Developer < Employee
  include Reviewer # including method into class Employee
  prepend Analyst # prepending method to class Employee

  # instance method to class Employee
  def name
    puts "Hi. This is Developer"
    super rescue nil
  end
end

# creating instance variable
developer_1 = Developer.new

# singleton method from instance variable
def developer_1.name
  puts "Hi. This is developer_1"
  super
end

# extending method to class Employee
developer_1.extend(Manager)
developer_1.name

Prints:

Hi. This is developer_1
Hi. This is Manager
Hi. This is Analyst
Hi. This is Reviewer
Hi. This is Developer
Hi. This is Employee

Ruby method precedence order

1. singleton
2. extend
3. prepend
4. class (instance)
5. include
6. super

2 Responses to “Ruby method lookup

  • Hi Srinidhi! Awesome post! I learn a lot from reading your Ruby posts

    • adminsrini
      6 years ago

      Thanks Akshat. There are many posts like these. Hope it helps many people like you. 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *