Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Ruby中的singleton类中调用singleton方法?_Ruby_Class_Module_Singleton - Fatal编程技术网

在Ruby中的singleton类中调用singleton方法?

在Ruby中的singleton类中调用singleton方法?,ruby,class,module,singleton,Ruby,Class,Module,Singleton,考虑以下Ruby代码: module MyModule class << self def process_item(item) item.capitalize end def foo=(item) @foo_ref=process_item(item) end def foo @foo_ref end self.foo = "initial foo" end end 模块M

考虑以下Ruby代码:

module MyModule
  class << self

    def process_item(item)
      item.capitalize
    end

    def foo=(item)
      @foo_ref=process_item(item)
    end

    def foo
      @foo_ref
    end

    self.foo = "initial foo"
  end
end
模块MyModule

类可以将默认值定义为:

module MyModule
  class << self

    def process_item(item)
      item.capitalize
    end

    def foo=(item)
      @foo_ref=process_item(item)
    end

    def foo
      @foo_ref ||= "initial foo"
    end
  end
end
模块MyModule

实际上,将
foo\u ref
实例变量设置为初始值是一个很好的解决方案。谢谢是否有其他方法可以在类定义中设置此变量(访问元类而不是单例类)?您也可以使用
self.foo=
MyModule
范围进行设置。(在
类看起来如此明显之后!非常感谢您的帮助:在类定义中,
self
是类,所以正如错误消息所说,您正在调用singleton类上的
foo=
方法,而此方法不存在。