Any Ruby guru that explain this?
class Bar
@@x = 10
def self.test
return @@x
end
end
class Foo < Bar
@@x = 20
end
puts Bar.test # 20 why not 10?
puts Foo.test # 20
When i run this from TextMate. I would expect that
puts Bar.test returns 10
and
puts Foo.test returns 20
But for some reason (that i would love to know) @@x in Foo updates Bar as-well, which is the super class. What is it i’m missing?
This is to be expected. Class variables are shared within the hierarchy. See section in Wikipedia: http://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Variables_and_Constants#Class_Variables
Compare this to class instance variables, which are private to that class only.