1

我在 ruby​​ 文档的module_function中看到了这个例子。我不明白 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 对象能够访问新代码?谢谢。

4

1 回答 1

5

运行 module_function 会在模块级别复制一个函数,也就是说,它等价于以下代码:

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

  def one
    "This is the new one"
  end
end

Mod.one并且one是不同的方法。第一个可以从任何地方调用,当您将模块包含在类中时,第二个成为实例方法。

于 2011-03-01T12:12:54.463 回答