Looking for an explanation why in the following example in Module.class_eval block, class variables lookup does not work:
class MyClass
@@myvar = 123
def self.myvar_getter
@@myvar
end
end
class MyClass
p "#{self}, #{self.object_id}, #{singleton_class.object_id}"
# output: "MyClass, 21055520, 21055500"
p myvar_getter # class method lookup working
# output: 123
p @@myvar # class variable lookup working
# output: 123
end
MyClass.class_eval do
p "#{self}, #{self.object_id}, #{singleton_class.object_id}"
# output: "MyClass, 21055520, 21055500"
p myvar_getter # class method lookup working as expected
# output: 123
p @@myvar # class variable lookup NOT working (why ?)
# output: -- following exception --
# a.rb:47: warning: class variable access from toplevel
# a.rb:47:in `block in <main>': uninitialized class variable
# @@myvar in Object (NameError)
end
As you may see the scope seems to be identical, self is the same, class method :myvar_getter is found in both cases, but class variable @@myvar is unexpectedly looked up in Object class within class_eval block.
Can anybody explain this behavior other than because ?
class_variable_get/setexplicitly on the class in question.class_variable_get/setmethods. I've even read great article of Yehuda Katz about metaprogramming in Ruby where are described nuances between scope, method resolution and method definition. But nothing explains issue from the question. Is there even another concept that differentiates variables lookup ?