Ruby元编程:初始化singleton_class变量 [英] Ruby metaprogramming: Initialize singleton_class variable
本文介绍了Ruby元编程:初始化singleton_class变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
- 为什么
Foo.val
在调用Foo.set
之前返回nil
而不是"foo"
? - 是否有用于初始化类评估中的
@val
的机制? -
@val = "foo"
存储在哪个范围内?
- Why does
Foo.val
returnnil
instead of"foo"
before callingFoo.set
? - Is there any mechanism for initializing
@val
on class evaluation? In which scope is
@val = "foo"
stored into?
class Foo
class << self
@val = "foo"
attr_reader :val
def set(val)
@val = val
end
end
end
p Foo.val # nil
Foo.set("bar")
p Foo.val # "bar"
推荐答案
您可以像这样在Foo中初始化@val
:
You can initialize @val
in Foo like this:
class Foo
@val = "foo"
class << self
attr_reader :val
def set(val)
@val = val
end
end
end
p Foo.val #=> "foo"
Foo.set("bar")
p Foo.val #=> "bar"
您的代码不是在Foo上而是在Foo的元类上初始化@val
Your code initializes @val
not on Foo, but on Foo's metaclass
这篇关于Ruby元编程:初始化singleton_class变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文