0
0
Rubyprogramming~5 mins

Method lookup chain in Ruby

Choose your learning style9 modes available
Introduction

The method lookup chain shows how Ruby finds the code to run when you call a method on an object. It helps understand which method runs if many have the same name.

You want to know which method will run when you call a method on an object.
You have multiple classes and modules with methods of the same name and want to see the order Ruby checks them.
You want to debug why a method behaves differently than expected.
You want to understand how Ruby handles inheritance and modules mixed into classes.
Syntax
Ruby
object.method(:method_name).owner

This code shows which class or module owns the method Ruby will run.

You can also use Module#ancestors to see the full lookup chain.

Examples
This shows that the hello method called on b is owned by class B, because B overrides A's method.
Ruby
class A
  def hello
    puts 'Hello from A'
  end
end

class B < A
  def hello
    puts 'Hello from B'
  end
end

b = B.new
p b.method(:hello).owner
This shows that the greet method comes from module M included in class C.
Ruby
module M
  def greet
    puts 'Hi from M'
  end
end

class C
  include M
end

c = C.new
p c.method(:greet).owner
This shows that to_s is owned by Ruby's Object class, because D does not define it.
Ruby
class D
end

d = D.new
p d.method(:to_s).owner
Sample Program

This program shows which speak method runs when called on child. It also prints the owner of the method and the full method lookup chain for class Child.

Ruby
module M1
  def speak
    puts 'Speak from M1'
  end
end

module M2
  def speak
    puts 'Speak from M2'
  end
end

class Parent
  def speak
    puts 'Speak from Parent'
  end
end

class Child < Parent
  include M1
  include M2
end

child = Child.new
child.speak
p child.method(:speak).owner
p Child.ancestors
OutputSuccess
Important Notes

The method lookup chain starts from the object's class, then checks included modules in reverse order of inclusion, then parent classes.

Modules included later override methods from modules included earlier.

You can use ancestors to see the full chain Ruby uses to find methods.

Summary

The method lookup chain shows where Ruby finds a method to run.

It helps understand method overriding and module inclusion order.

Use object.method(:name).owner and Class.ancestors to explore it.