我在ruby文档中看到了module_function中的示例.我不明白代码的后半部分,其中Mod.one返回旧的"this is 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"
Run Code Online (Sandbox Code Playgroud)
为什么Mod.one返回旧代码但Cls对象能够访问新代码?谢谢.
运行module_function在模块级别创建一个函数的副本,也就是说,它等效于以下代码:
module Mod
def Mod.one
"This is one"
end
def one
"This is the new one"
end
end
Run Code Online (Sandbox Code Playgroud)
Mod.one并且one是不同的方法.第一个可以从任何地方调用,第二个在模块中包含模块时成为实例方法.
| 归档时间: |
|
| 查看次数: |
549 次 |
| 最近记录: |