访问类变量?
class Foo
@@default = "default"
p instance_variables
p class_variables
class << self
p instance_variables
p class_variables
# How do I access the @@default variable here?
end
end
class Foo
@@default = "default"
p instance_variables
p class_variables
class << self
p instance_variables
p class_variables
# How do I access the @@default variable here?
end
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
与在任何其他地方执行此操作的方式相同:
@@default
。我不确定
p ..
应该做什么(Ruby 不是我的母语),但这可行The same way you do it in any other place:
@@default
.I'm not sure what
p ..
is supposed to do (Ruby isn't my native language), but this works这个问题很有趣,因为它本质上是问“元类有没有办法引用它的“真实”类?
据我所知,答案是“不”,因为所有“向上”祖先指针Ruby 还指向元类,因此在其中一个中运行
class_variables()
会告诉您有关其类实例变量的信息,因此,您必须通过名称或引用来引用对象。只需在进入元类上下文之前建立一个句柄...This question is kind of interesting because it essentially asks "is there any way for the metaclass to reference its "real" class?
And as far as I can tell, the answer is "no", because all of the "upward" ancestor pointers Ruby keeps also point to metaclasses, and so running
class_variables()
in one of them will tell you about its class instance variables. So, you have to reference objects by name or just establish a handle before entering the metaclass context...