module_function example in the ruby documentation
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.
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.
精彩评论