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

age*_*217 14 ruby class-variables class-instance-variables

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

def MyClass
  @@foo = 'bar' # Should not do this.
  @foo = 'bar'  # Should do this.
end
Run Code Online (Sandbox Code Playgroud)

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

sep*_*p2k 27

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

class Foo
  @@foo = 42

  def self.foo
    @@foo
  end
end

class Bar < Foo
  @@foo = 23
end

Foo.foo #=> 23
Bar.foo #=> 23
Run Code Online (Sandbox Code Playgroud)

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

class Foo
  @foo = 42

  def self.foo
    @foo
  end
end

class Bar < Foo
  @foo = 23
end

Foo.foo #=> 42
Bar.foo #=> 23
Run Code Online (Sandbox Code Playgroud)

这通常更有用.


Nul*_*ion 6

小心; 类@@variables和实例@variables不是一回事.

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

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