Search code examples
rubyinstance-variablesclass-variablesclass-instance-variables

Class Variables


Explain please, I can not understand.

class Foo
  @a = 123
  @@b = 123
end

What are the advantages of variable objects-classes and the class variables? When should I use first, and in which the second?


Solution

  • Instance level variables area created anew for each instance of the class. For example, a variable @id should probably be unique for each instance of Foo. However, there may be some values that should be the same for every instance of the type. In that case, a class variable would be more appropriate.

    One important side effect of class level variables is that they are shared amongst derived classes as well. This means that changing the value in a subclass of 'Foo' will change it for 'Foo' objects as well. This may be what you want, but it can be a bit surprising to find out the hard way.

    For example:

    class Foo
      @@some_var = 1
      def bar
        puts(@@some_var)
      end
    end
    
    class Baz < Foo
      def perhaps_unexpected
        @@some_var = 10
        Foo.new.bar  #prints '10'
      end
    end