为什么要在Ruby中避免使用@@ class_variables?

我知道有人说在Ruby中应该避免使用类变量(例如@@class_var ),而应该在类范围中使用实例变量(例如@instance_var ):

 def MyClass @@foo = 'bar' # Should not do this. @foo = 'bar' # Should do this. end 

为什么在Ruby中使用类变量不受欢迎?

类变量经常受到诽谤,因为它们有时会对inheritance行为造成混淆:

 class Foo @@foo = 42 def self.foo @@foo end end class Bar < Foo @@foo = 23 end Foo.foo #=> 23 Bar.foo #=> 23 

如果您使用类实例变量,则会得到:

 class Foo @foo = 42 def self.foo @foo end end class Bar < Foo @foo = 23 end Foo.foo #=> 42 Bar.foo #=> 23 

这通常更有用。

小心; class @@variables和instance @variables不是一回事。

实质上,当您在基类中声明一个类变量时,它与所有子类共享。 在子类中更改其值将影响基类及其所有子类,一直到inheritance树。 这种行为通常正是所期望的。 但同样经常,这种行为不是程序员想要的行为,而且会导致错误,特别是如果程序员最初并不期望该类被其他人子类化。

来自: http : //sporkmonger.com/2007/2/19/instance-variables-class-variables-and-inheritance-in-ruby