3 ms·
Another one: class variables! # Define two class variables in two different classes: class MyClass @@base = 1 end class OtherClass
by judofyr 15y ago
Another one: class variables!
# Define two class variables in two different classes:
class MyClass
@@base = 1
end
class OtherClass
@@base = 2
end
# Define it in the superclass too:
class Object
@@base = 3
end
class MyClass
# Magic! The subclass-variable has now changed!
p @@base # => 3
end
class OtherClass
# In both classes in fact:
p @@base # => 3
# And finally, let's reset this:
@@base = 4
end
class Object
# Whoops, this changes the superclass too:
p @@base # => 4
end
Explanation: Two class variables with the same name can't exists in the
same class hierachy. Therefore, class variable lookup (and setter) will
always traverse to the upmost-class where the variable is defined.
(Hope you don't mind that I wrote these in two different posts.)