Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 504
Nishant Upadhyay Avatar asked Mar 31 '26 04:03

Nishant Upadhyay


1 Answers

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.

like image 99
Maxim Pontyushenko Avatar answered Apr 02 '26 21:04

Maxim Pontyushenko