When I use Class.new
, for some reason the class variables of the resulted classes interfere with each other:
# ruby 2.1.6p336 (2015-04-13 revision 50298) [i686-linux]
result = Class.new do
p self # #<Class:0xb7cd5624>
@@foo = 1
def foo
p @@foo
end
end
result2 = Class.new do
p self # #<Class:0xb7cd54d0>
@@foo = 2
def foo
p @@foo
end
end
result.class_variable_set(:@@foo, 3)
result.new.foo # expected 3, output 3
result2.new.foo # expected 2, output 3
Why? What is happening under the hood?
Also there are related Warning messages but I am unable to understand what they mean, neither to find a good description.
warning: class variable access from toplevel
The closest clues I've found so far are:
The access to the class variable is considered top level because the class keyword does not define a class name that would provide a scope to hold the class variable.
(c) http://japhr.blogspot.ru/2009/06/more-information-about-class-variables.html
Since you're not creating a class with the
class
keyword, your class variable is being set onObject
, notTest
(c) https://stackoverflow.com/a/10712458/1432640
Could somebody please describe in details why it happens and why it is so different from when I use class
keyword?