派生类共享类变量?

时间:2011-05-11 13:07:26

标签: ruby inheritance

我有一个班级Cache和两个派生班级FooBar(简化,但原则相同)。

class Cache

  @@test = []

  def self.test
    @@test
  end

 def self.add(value)
   @@test << value
 end

end

class Foo < Cache
end

class Bar < Cache
end

运行以下内容可以让我得出结论:@@ test不是FooBar唯一的,但只是Cache唯一,这是我不想要的也不期望。

Foo.add(1) #[1]
Bar.add(2) #[1,2]
puts Foo.test #[1,2]

这不应该是:

Foo.add(1) #[1]
Bar.add(2) #[2]
puts Foo.test #[1]

如何获得我想要的行为?为什么Ruby这么奇怪?

1 个答案:

答案 0 :(得分:0)

在这种情况下,解决方案不是使用静态类,而是使用我想要的类的2个实例,并将它们存储在静态变量中。

相关问题