开发者

Derived Class shares class variables?

开发者 https://www.devze.com 2023-03-04 08:38 出处:网络
I have a class Cache and 2 derived classes Foo and Bar (simplification, but the principle is the same).

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消