Ruby Method Lookup with Multiple Modules

Modules are wrapped in an anonymous class when they’re included in a Ruby class. Modules are added to the right of the class that includes them when they’re included in a class.

module M; end
class A
  include M
end
p A.ancestors # => [A, M, Object, Kernel, BasicObject]

The M module is added to the ‘right’ of the A class in the method lookup chain (aka the ancestors array) when M is included.

When multiple modules are included, they’re each added to the right of the class that includes them in the method lookup chain. The last module included in a class will be the first module in the method lookup chain (the leftmost module in the method lookup chain).

module X
  def hi
    "X#hi"
  end
end

module Y; end

module Z
  def hi
    "Z#hi"
  end
end

class Something
  include X
  include Y
  include Z
end
p Something.ancestors # => [A, Z, Y, X, Object, Kernel, BasicObject]
p Something.new.hi # => "Z#hi"

The Ruby method lookup process will invoke methods in modules included last in a class before modules included earlier.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s