ruby - ruby 文档中的 module_function 示例

标签 ruby ruby-1.9.1

我在 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.oneone 是不同的方法。第一个可以从任何地方调用,第二个在您将模块包含在类中时成为实例方法。

关于ruby - ruby 文档中的 module_function 示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5153648/

相关文章:

ruby-on-rails - Rails 在 ruby​​ 1.9.1 上初始化非常慢

Ruby 需要 'file' 和相对位置

mysql - 将数据库的第一个实例导出到第二个实例

javascript - 从 JavaScript 运行 Ruby 库

ruby - 性能:ruby CSV.foreach 与 CSV.parse

ruby-on-rails - 为什么我的 Rails 应用程序无法使用 Passenger 3、RVM 和 Rails 3.1 加载?

ruby - 将自定义条目添加到 Cocoapods 生成的 acknowledgments.plist 中

ruby-on-rails - 如何在 ruby​​ 1.9 上运行 Rails 1.2.5 应用程序?