Ruby 在 Object 中查找类变量而不是特定类 [英] Ruby looks for class variable in the Object instead of specific class
问题描述
这部分有效:
class Example1
@@var1= "var1 in the Example1"
def get_var1
@@var1
end
end
example1 = Example1.new
example1.get_var1
# => "var1 in the Example1"
但是如果我尝试使用 eigenclass:
but if I try eigenclass:
def example1.get_var1
@@var1
end
example1.get_var1
# NameError: uninitialized class variable @@var1 in Object
# from (pry):128:in `get_var1'
Ruby 在 Object
中查找 @@var1
而不是 Example
.
Ruby looks @@var1
in the Object
instead of the Example
.
我在 Ruby 1.9.3 和 2.0 中测试了这段代码,结果相同.
I have tested this code in the Ruby 1.9.3 and 2.0 with the same result.
为什么会这样?
第二件事,我们能不能把它关掉(这样 example.get_var1
就不会在 Object 中寻找类变量)?
Why does it happening?
The second thing, can we turn it off (so example.get_var1
won't look for class variables in the Object)?
推荐答案
看起来类变量查找的词法范围有点古怪.据我所知,因为你不在
It appears as though the lexical scope for class variable lookup is kind of wacky. As near as I can tell, because you're not inside the
class Example1
end
block,ruby 不会在您的类中查找 @@var,而是从 Object 中查找.如果你想从你的班级明确地得到它,你可以这样做:
block, ruby doesn't look up @@var in your class, but rather from Object. If you want it explicitly from your class, you can do:
def example1.get_var
self.class.class_variable_get(:@@var1)
end
我偶然发现了 https://www.ruby-forum.com/topic/1228428 在寻找答案的同时.他们谈论的是 1.8.7,但它似乎也适用于更高版本.
I stumbled across https://www.ruby-forum.com/topic/1228428 while searching for the answer. They're talking about 1.8.7, but it appears to apply to later versions as well.
这篇关于Ruby 在 Object 中查找类变量而不是特定类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!