Search code examples
rubyclass-variables

Are these class variables?


In the snippet below,

class MyClass
  class << self    
    @@variable1 = 'foo'

    def my_method
      @variable2 = 'bar'
    end
  end
end

are @@variable1 and @variable2 class variables? Said differently, is the above snippet equivalent to this one:

 class MyClass
    @@variable1 = 'foo'

    def self.my_method
      @@variable2 = 'bar'
    end
 end

EDITED

@suvankar, thanks for answering. The second snippet was a typo and I edited it to include 'self'. I'm actually not entirely sure that in the first snippet, variable2 is a class variable. For example, if I load the first snippet into irb, and type:

  >> MyClass.class_variables
  => [@@variable1]

  >> MyClass.instance_variables
  => [@variable2]

So it seems like variable1 is a class variable (no surprise there). But variable2 is an instance variable of the class MyClass.


Solution

  • You are correct that @@variable1 is a class variable and @variable2 is an instance variable of the class. The two snippets are not equivalent because @@variable2 (only defined in snippet two) is also a class variable.

    (Note: I assume that your irb output has a typo and that it should have included @variable2 and only after invoking MyClass.my_method.)