Derived Class shares class variables?
I have a class Cache and 2 derived classes Foo and Bar (simplification, but the principle is the same).
class Cache
@@test = []
def self.test
@@test
end
def self.add(value)
@@test << value
end
end
class Foo < Cache
end
class Bar < Cache
end
Running the following leads me to conclude that the @@test is not unique to Foo and Bar, but is only unique to Cache, which is something开发者_Python百科 I don't want nor expect.
Foo.add(1) #[1]
Bar.add(2) #[1,2]
puts Foo.test #[1,2]
Isn't this supposed to be:
Foo.add(1) #[1]
Bar.add(2) #[2]
puts Foo.test #[1]
How can I get the behaviour that I want? Why is Ruby doing this so strange?
The solution in this case was not to use static classes, but just 2 instances of the class I wanted and storing them in a static variable.
加载中,请稍侯......
精彩评论