我在 module_function 中看到了这个例子在 ruby 文档中。我不明白代码的后半部分,其中 Mod.one 返回旧的“这是一个”,而 c.one 返回更新后的“这是新的”。这是怎么发生的
这是文档中的实际代码
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"
为什么 Mod.one 返回旧代码但 Cls 对象能够访问新代码? 谢谢。
最佳答案
运行 module_function 会在模块级别复制一个函数,也就是说,它等同于以下代码:
module Mod
def Mod.one
"This is one"
end
def one
"This is the new one"
end
end
Mod.one
和 one
是不同的方法。第一个可以从任何地方调用,第二个在您将模块包含在类中时成为实例方法。
关于ruby - ruby 文档中的 module_function 示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5153648/