问题
This part works:
class Example1
@@var1= "var1 in the Example1"
def get_var1
@@var1
end
end
example1 = Example1.new
example1.get_var1
# => "var1 in the Example1"
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 looks @@var1
in the Object
instead of the Example
.
I have tested this code in the Ruby 1.9.3 and 2.0 with the same result.
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)?
回答1:
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 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
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.
来源:https://stackoverflow.com/questions/24510948/ruby-looks-for-class-variable-in-the-object-instead-of-specific-class