Search code examples
rubyinheritancemodulesingleton-methods

Module methods in Ruby


Here is my code:

module Star
  def Star.line
    puts '*' * 20
  end
end

module Dollar
  def Star.line
    puts '$' * 20
  end
end

module At
  def line
    puts '@' * 20
  end
end

include At
Dollar::line # => "@@@@@@@@@@@@@@@@@@@@"
Star::line   # => "$$$$$$$$$$$$$$$$$$$$"
Dollar::line # => "@@@@@@@@@@@@@@@@@@@@"
line         # => "@@@@@@@@@@@@@@@@@@@@"

Can anyone explain how I get this result? I do not understand the method lookup flow here.


Solution

  • This is how I see it:

    Dollar::line

    There is no such method defined in this module so It's calling At::line because you included this module.

    Star::line

    It uses last defining from Dollar module(it goes after original Star definition so it's overridden).

    Dollar::line

    Third call is the same as the first one.

    line

    And the last one is At::line because You made an include.