【问题标题】:Accessing module methods from a class in that module?从该模块中的类访问模块方法?
【发布时间】:2013-12-05 17:06:30
【问题描述】:

在 Ruby 2.0 下,从模块中的类访问模块方法的正确方法是什么?

例如,如果我有

module Foo
    class Foo
        def do_something
            Foo::module_method
        end
    end

    def self.module_method
        puts 'How do I call this?'
    end
end 

我明白了,

./so-module.rb:7:in do_something': undefined methodmodule_method' for Foo::Foo:Class (NoMethodError) from ./so-module.rb:16:in `'

定义模块方法以便我可以从类Foo 访问它的正确方法是什么?

【问题讨论】:

  • 你确定这是你得到的错误吗?我得到“NoMethodError: undefined method `module_method' for Foo:Module”。
  • @AndrewMarshall,你说得对,从我的实际代码到将其简化为示例的翻译过程中丢失了一些东西。让我看看我能不能弄明白。
  • 啊,好吧,我也遇到了类名与模块名相同的问题,这导致了奇怪的事情发生,所以我已经更正了。
  • 您能否更新您的问题以反映这些变化?
  • 我实际上并没有得到完全相同的错误,即使更改了脚本,但我会更新它以更准确地反映我原来的问题

标签: ruby module


【解决方案1】:

你必须在模块的单例类上定义方法:

module Foo
  class Bar
    def do_something
      Foo.module_method
    end
  end

  def self.module_method
    'Success!'
  end
end

Foo::Bar.new.do_something  #=> "Success!"

【讨论】:

【解决方案2】:

请看下面的代码:

module Foo
    class Bar
        include Foo
        def do_something
            module_method
        end
    end
    def module_method
        puts 'How do I call this?'
    end
end

b = Foo::Bar.new
b.do_something

结果:

How do I call this?

您甚至可以尝试添加以下代码:

b1 = Foo::Bar::Bar.new
b1.do_something

这很棘手,结果相同:

How do I call this?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多