Stelyian Stoyanov
Stelyian Stoyanov

Reputation: 17

objects' method lookup path (modules & method override)

I cannot figure out how come the object is so smart to disregard the following block of code even if performed for the first time.

The method it is searching for is on each module

class A
  include B,C,D,B
end

Does ruby keeps an array of module names on the side (as it obviously calls D)?

Upvotes: 0

Views: 353

Answers (1)

Holger Just
Holger Just

Reputation: 55833

I'm not 100% I understand your question but I try my best...

Ruby actually remembers which modules are included into a class and merges these modules into the lookup path for methods. You can ask a class for its included methods my using A.included_modules

Methods from included modules are put on top of the modules defined in the current class. Please see this example:

class X
  def foo
    puts 'Hi from X'
  end
end

module AnotherFoo
  def foo
    puts "Hi from AnotherFoo"
    super
  end
end

class Y < X
  include AnotherFoo
end

y = Y.new
y.foo
# Hi from another foo
# Hi from X

class Y < X
  include AnotherFoo
  def foo
    puts "Hi from Y"
    super
  end
end

y.foo
# Hi from Y
# Hi from another foo
# Hi from X

You can see the method resolution order: the child class -> the included modules -> the parent class. You can also see that modules are always included only once. So if a class already includes a module, it will not be re-included again.

Upvotes: 2

Related Questions