Well much has been said about class variables in Ruby and how good and bad they are. When a C++/Java Programmer comes to Ruby, his search of static class variables begin immediately and unfortunately current Text on Ruby seems to suggest that, class variables are apt equivalents of static variables.
Answer is yes and no. When you use class variables, remember they are the same for all instance of the classes, even derived classes will reflect upon the same value and if you modify the class variables in one of those derived classes, it would be changed for all the other classes, which inherit the same parent. Got the picture?
Ok, Here is scary bit of code:
@@avar = 1
class A
@@avar = "hello"
end
puts @@avar # => helloThere is nothing special about code, if you look closely, because if you don’t define a class and declare class variables outside class definition, by default it gets hooked into Object class and since all the classes one way or the other end up inheriting from Object class, if you change the class variable declared at Object class scope in any of the classes, it would be reflected back in class variable held by Object class(bullshit, its the same variable)
Often, thats not.. what you want. Enter class instance variables, which are nice and dandy variables.. which are again avaialble to all the instances of the class and if you change the variable in one instance of the class, it would be reflected everywhere. But unlike class variables, they are not inherited.
Without much ado, here the sweet spot:
class A
@foo = "bar"
class << self; attr_accessor: foo; end
end
class B < A
end
p A.foo #=> bar
p B.foo #=> nil
B.foo = "blah"
p B.foo #=> blahThe overhead is, if you have to access them from instance methods of classes, then you will have to use self.class.foo