Why should @@class_variables be avoided in Ruby? Why should @@class_variables be avoided in Ruby? ruby ruby

Why should @@class_variables be avoided in Ruby?


Class variables are often maligned because of their sometimes confusing behavior regarding inheritance:

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

If you use class instance variables instead, you get:

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

This is often more useful.


Be careful; class @@variables and instance @variables are not the same thing.

Essentially, when you declare a class variable in a base class, it’s shared with all subclasses. Changing its value in a subclass will affect the base class and all of its subclasses all the way down the inheritance tree. This behavior is often exactly what’s desired. But equally often, this behavior is not what was intended by the programmer, and it leads to bugs, especially if the programmer did not originally expect for the class to be subclassed by someone else.

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