1

I saw the example in the module_function in the ruby documentation. I do not understand the latter part of the code where Mod.one returns the old "this is one" and the c.one returns the updated "this is the new one". How does this happen

This is the actual code from the documentation

 module Mod
   def one
     "This is one"
   end
   module_function :one
 end

 class Cls
   include Mod
   def call_one
     one
   end
 end

 Mod.one     #=> "This is one"
 c = Cls.new
 c.call_one  #=> "This is one"

 module Mod
   def one
     "This is the new one"
   end
 end

 Mod.one     #=> "This is one"
 c.call_one   #=> "This is the new one"

Why Mod.one returns the old code but the Cls object is able to access the new one? Thanks.

Community
  • 1
  • 1
felix
  • 11,304
  • 13
  • 69
  • 95

1 Answers1

5

Running module_function makes a copy of a function at the module level, that is, it's equivalent to the following code:

module Mod
  def Mod.one
    "This is one"
  end

  def one
    "This is the new one"
  end
end

Mod.one and one are different methods. The first one can be called from anywhere, the second one becomes an instance method when you include the module in a class.

Andrew Grimm
  • 78,473
  • 57
  • 200
  • 338
Michiel de Mare
  • 41,982
  • 29
  • 103
  • 134