Read more

How Ruby method lookup works

Henning Koch
March 17, 2014Software engineer at makandra GmbH

When you call a method on an object, Ruby looks for the implementation of that method. It looks in the following places and uses the first implementation it finds:

  1. Methods from the object's singleton class (an unnamed class that only exists for that object)
  2. Methods from prepended modules Show archive.org snapshot (Ruby 2.0+ feature)
  3. Methods from the object's class
  4. Methods from included modules
  5. Methods from the class hierarchy (superclass and its ancestors)

Example

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

Let's say we have the following class hierarchy:

class Superclass

  def action
    puts "Superclass"
  end 

end


module IncludedModule

  def action
    puts "Included module"
    super
  end
  
end


module PrependedModule

  def action
    puts "Prepended module"
    super
  end
  
end

module SingletonModule

  def action
    puts "Singleton class"
    super
  end

end

class Klass < Superclass
  include IncludedModule
  prepend PrependedModule

  def action
    puts "Klass"
    super
  end
  
end

... and we call a method like this:

instance = Klass.new
instance.extend(SingletonModule)
instance.action

Then we get an output as expected:

Singleton class
Prepended module
Klass
Included module
Superclass

If you are interested in why it works like that, you will find some more background here.

Henning Koch
March 17, 2014Software engineer at makandra GmbH
Posted by Henning Koch to makandra dev (2014-03-17 11:06)