在Ruby中的singleton类中调用singleton方法?
考虑以下Ruby代码:在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
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=
方法,而此方法不存在。