Why should @@class_variables be avoided in Ruby?

前端 未结 2 2004
没有蜡笔的小新
没有蜡笔的小新 2021-02-13 11:55

I know that some say that class variables (e.g. @@class_var) should be avoid in Ruby and should use the an instance variable (e.g. @instance_var) in th

2条回答
  •  庸人自扰
    2021-02-13 12:15

    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

提交回复
热议问题