This was actually inspired by some thoughts at a new_haven.rb meeting I wasn’t able to attend, reintroduced in a RubyTalk thread, and solidified in another blog entry that’s worth a look.

The topic here is simple, and it’s that for most common needs, there is absolute no reason to use class variables. I will show how you can use class instance variables to avoid the problems associated with class variables in most cases at the end of this article, but first, take a look at two compelling and mind melting reasons for *not* using class variables.

From Gary Wright:

>> class A
 >> @@avar = 'hello'
 >> end
=> "hello"
 >> A.class_variables
=> ["@@avar"]
 >> A.class_eval { puts @@avar }
NameError: uninitialized class variable @@avar in Object
        from (irb):5
        from (irb):5
 >> class A
 >> puts @@avar
 >> end
hello
=> nil
 >> class A
 >> def get_avar
 >> @@avar
 >> end
 >> end
=> nil
 >> a = A.new
=> #
 >> a.get_avar
=> "hello"
 >>   a.instance_eval { puts @@avar }
NameError: uninitialized class variable @@avar in Object
        from (irb):16
        from (irb):16
 

And the real scary one, from David A. Black:

   @@avar = 1
  class A
    @@avar = "hello"
  end
  puts @@avar  # => hello

  A.class_eval { puts @@avar }  # => hello

Yes, there are reasons why both of these problems occur. Yes, they are likely to give you a headache.

If you’re just looking to store some data in a variable which is unique to your class, but accessible from instances or externally, why not just use instance variables?

>> class A
>>   @foo = "bar"
>>   class << self; attr_reader :foo; end
>> end
=> nil
>> A.foo
=> "bar"

Yup, classes are just regular old ruby objects, and class instance variables are just regular old instance variables. This avoids the above problems, as well as simplifies the concepts of where your variables actually live.

Yeah, maybe @@foo is easier to type than self.class.foo
But good luck debugging it! :)