Why should @@class_variables be avoided in Ruby?

前端 未结 2 1999
没有蜡笔的小新
没有蜡笔的小新 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:03

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

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

    If you use class instance variables instead, you get:

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

    This is often more useful.

提交回复
热议问题