Another question about class variables actually. My understanding of
class variables lookup is that it is not different from the methods
lookup.
They are not the same and are closer to the way constants are looked up but not quite the same as that either...
Indeed, an instance object look at its class's class variables
and then go through superclass and module all the way up to BasicObject.
Not really, the lookup is more accurately associated with the lexical context of the reference than the dynamic context. In your B.print method, the lexical scope is actually the class B and so that is the starting point for the class variable resolution. This is distinctly different than the way instance variables are resolved.
Now why does not it apply to Classes object:
===
class Class
@@test = "test"
end
class B
def self.print
puts @@test
end
end
B.print
In this case B.print fails with:
module.rb:7:in `print': uninitialized class variable @@test in B
(NameError)
from module.rb:11
Since B's class is Class that should be fine. Obviously I must be
missing something here.
Consider the following:
class A
@@foo = "hello"
def foo
@@foo
end
def foo_ieval
42.instance_eval { @@foo }
end
def foo_ceval
Array.class_eval { @@foo }
end
end
puts A.new.foo # "hello"
puts A.new.foo_ieval # "hello"
puts A.new.foo_ceval # "hello"
Array.class_eval { @@foo } # undefined
The lexical scope for foo, foo_ieval, and foo_ceval is the enclosing class/end block for A while the lexical scope for the final Array.class_eval is the top level. For the three methods, they all resolve to the same class variable owned by the class A while the class_eval outside of A's definition block resolves to the top level class, Object.
Gary Wright
···
On Mar 6, 2011, at 11:04 PM, JP Billaud wrote: