Question

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.

Was it helpful?

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.)

OTHER TIPS

Answering to first question: yes, variable1 and variable2 class variables

Second question: Above two snippet are not same.

Explanation:

In the first snippet 'my_method' is class method and in the second snippet 'my_method' is instance method.

Following snippet is similar to first snippet, where my_method is a class method of MyClass

class MyClass
    @@variable1 = 'foo'

    def self.my_method
      @@variable2 = 'bar'
    end
 end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top