Ruby's method lookup

In Ruby, method lookup is the process of finding and executing the appropriate method for a given object. It involves traversing the class hierarchy to locate the method definition. Ruby follows a specific order, known as the method lookup path or method resolution order, to determine which method to invoke. The method lookup path ensures that methods are resolved correctly based on inheritance and module inclusion.

Let's consider an example to understand method lookup in Ruby:

module A
  def greet
    puts "Hello from module A!"
  end
end

module B
  def greet
    puts "Hello from module B!"
  end
end

class Base
  def greet
    puts "Hello from Base class!"
  end
end

class Derived < Base
  include A
  include B
end

obj = Derived.new
obj.greet

In this example, we have two modules, A and B, and two classes, Base and Derived. The Derived class inherits from Base and includes modules A and B.

When we call the greet method on the obj object, Ruby goes through the method lookup path to find the appropriate implementation of the greet method. The lookup path is as follows:

  1. The obj object itself.

  2. The Derived class.

  3. The included modules, in reverse order of inclusion (B and then A).

  4. The superclass (Base class in this case).

Ruby searches for the greet method in each of these locations, stopping when it finds the first matching method. The search starts from the left and proceeds to the right.

In our example, the greet method is found in module B, so that implementation is executed, and the output will be:

Hello from module B!

If we remove the include B line from the Derived class, Ruby will continue searching for the method and find it in module A:

class Derived < Base
  include A
end

obj = Derived.new
obj.greet

Output:

Hello from module A!

If we remove both the include B and include A lines, Ruby will continue searching and find the method in the superclass, Base:

class Derived < Base
end

obj = Derived.new
obj.greet

Output:

Hello from Base class!

This method lookup mechanism allows for flexible method resolution based on the inheritance hierarchy and the order of included modules. It supports the principle of "favor composition over inheritance" by enabling the use of multiple modules to provide additional functionality to a class.

Understanding Ruby's method lookup is crucial when dealing with complex class hierarchies and modules, as it ensures that the correct method is called at runtime based on the object's structure and the order of inclusion."

Last updated