【问题标题】:module_function in an IRB session?IRB 会话中的 module_function?
【发布时间】:2013-03-30 17:45:07
【问题描述】:

我很难理解为什么在接下来的 irb 会话中缺少 Module#module_function

> class << self      # open singleton for the session's object instance
>   p is_a? Module   # true
>   p respond_to? :module_function   # false ??
> end

我想达到什么目的?在 irb 会话中直接使用外部模块,即。无需将其包装在新模块中。外部模块使用 module_eval 动态创建方法,然后在新方法名称上调用 module_function。

> require 'dlx/normalize'  # true
> class << self
>   extend DLX::Normalize   # main
>   generic_bind 'laplace-inverse'  # calling DLX::Normalize.generic_bind
> end
NoMethodError: undefined method `module_function' for #<Class:#<Object:0x0000000092e6e0>>

我在这里缺少什么?使用class &lt;&lt; selfsingleton_class.module_exec 访问irb 中的最外层 模块类是否正确?即使类 Module 的后代,为什么 module_function 会丢失?

更新: 为了使我的问题更加明确,将上述代码包装在新的模块定义中确实有效。我不明白为什么需要这种包装。

> require 'dlx/normalize'  # true
> module Dummy
>   extend DLX::Normalize   # main
>   generic_bind 'laplace-inverse'  # calling DLX::Normalize.generic_bind
>                                   # this method calls module_function
> end
> Dummy.generated_laplace(1.234)    # got new module's method
>                                   # previous call to module_function
>                                   # did succeeded

【问题讨论】:

  • 能否请您更具体地描述您的困惑?
  • 外部模块使用Module#module_function。在 IRB 中使用 extend 添加模块的方法后,调用失败并显示 NoMethodError 其中不应缺少 module_function 方法。这是Module 定义的标准部分。

标签: ruby metaprogramming irb


【解决方案1】:
Module.new.respond_to? :module_function
=> false

还有

module Foo
  p respond_to? :module_function
end
=> false

所以你会在我期望的任何后代中得到相同的答案。

【讨论】:

  • 这很奇怪。 module Foo ; p respond_to? :module_function # false; def test; 42; end ; module_function :test ; endinclude Foo; test # 42 所以看起来module_function 不是 Module 类的方法。那是什么?
猜你喜欢
  • 2014-12-21
  • 1970-01-01
  • 2011-07-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多