【问题标题】:module_function example in the ruby documentationruby 文档中的 module_function 示例
【发布时间】:2011-07-06 10:26:53
【问题描述】:

我在 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 对象能够访问新代码? 谢谢。

【问题讨论】:

  • 我打算将callOne 编辑为call_one,但您在文档中注意到它是这样的。我会在某个阶段提交一份关于此问题的错误报告。

标签: ruby ruby-1.9.1


【解决方案1】:

运行module_function会在模块级别复制一个函数,也就是相当于下面的代码:

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

  def one
    "This is the new one"
  end
end

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-13
    • 1970-01-01
    • 1970-01-01
    • 2016-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-16
    相关资源
    最近更新 更多