使用class_eval和instance_eval访问Ruby类变量 [英] Accessing Ruby Class Variables with class_eval and instance_eval
问题描述
我有以下:
class Test
@@a = 10
def show_a()
puts "a: #{@@a}"
end
class << self
@@b = '40'
def show_b
puts "b: #{@@b}"
end
end
end
为什么以下工作:
Test.instance_eval{show_b}
b: 40
=> nil
但我无法访问 @@ b
直接?
Test.instance_eval{ @@b }
NameError: uninitialized class variable @@b in Object
同样,以下作品
t = Test.new
t.instance_eval{show_a}
a: 10
=> nil
但以下操作失败
t.instance_eval{ @@a }
NameError: uninitialized class variable @@a in Object
我不明白为什么我不能直接从 instance_eval
块中访问类变量。
I don't understand why I can't access the Class Variables directly from the instance_eval
blocks.
推荐答案
我刚刚在RubyKaigi派对时向Matz提出了同样的问题。我是半醉了,但他非常清醒,所以你可以把这作为最终的答案。
I just asked the same question to Matz during the RubyKaigi party. I was half-drunk, but he was perfectly sober, so you can take this as the definitive answer.
Anton是正确的 - 你不能访问类变量的原因instance_eval()是只是因为。甚至class_eval()共享同样的问题(Matz自己不完全确定class_eval(),直到我告诉他,我已经尝试了)。更具体地说:范围更广泛,类变量更像是常量而不是实例变量,因此切换self(作为instance_eval()和class_eval()do)在访问它们时不会产生任何影响。
Anton is right - the reason why you cannot access class variables through instance_eval() is "just because". Even class_eval() shares the same issue (Matz himself wasn't totally sure about class_eval() until I told him I'd already tried it). More specifically: scope-wise, class variables are more like constants than instance variables, so switching self (as instance_eval() and class_eval() do) is not going to make any difference when it comes to accessing them.
一般来说,避免类变量可能是个好主意。
In general, it might be a good idea to avoid class variables altogether.
这篇关于使用class_eval和instance_eval访问Ruby类变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!