【问题标题】:ruby NameError when including Singleton module in class belonging to another module在属于另一个模块的类中包含 Singleton 模块时的 ruby​​ NameError
【发布时间】:2011-02-16 16:41:18
【问题描述】:

当我尝试将 Singleton 模块包含在一个本身存在于模块中的类中时,它不起作用。这是一个例子:

require 'singleton'

module SomeModule
end

class SomeModule::SomeClass
  include Singleton

  def initialize
    @some_variable = 1
  end

  def output
    puts @some_variable
  end
end

SomeClass.instance.output

我得到的错误是:

未初始化的常量 对象::SomeClass (NameError)

我不确定如何告诉 Singleton 模块寻找 SomeModule::SomeClass 而不是 Object::SomeClass

【问题讨论】:

    标签: ruby module singleton mixins nameerror


    【解决方案1】:

    问题是您调用 SomeClass 类时没有预先添加模块名称。添加模块名称以使其工作:

    SomeModule::SomeClass.instance.output
    

    【讨论】:

    • 现在我看到了,这很明显。猜猜这只是那些日子之一。谢谢!
    猜你喜欢
    • 2020-04-17
    • 1970-01-01
    • 1970-01-01
    • 2015-02-10
    • 2016-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多