From: Calvin Bornhofen Date: 2012-09-21T22:02:01+09:00 Subject: Re: Class variables > --Quote > @@suits = ['C', 'D', 'H', 'S'] > > isn't what you would expect, so no one uses them. Rubyists use class > instance variables instead, e.g > > --End quote > > >From what I can see online > @@suits = ['C', 'D', 'H', 'S'] creates the array only once no matter how > many instances you have of the object. Is that not a good thing? > I don't understand why nobody is using this? > > isn't what you would expect, so no one uses them. Rubyists use class > instance variables instead, e.g. The @@ makes the variable a static-like variable as you know it from other OO-languages. The thing is, that this variable is not a static member of the class in the usual sense. It is consistent over the whole class hierarchy. So, if you change the value in one subclass, you change it for all classes. Sometimes that is what you want to have, but usually it is not. But, Ruby has an alternative: Since classes are also objects, you can declare a variable on the class level by using @ instead of @@. This makes the variable available to your class, and all subclasses, _but_ makes it a different variable for each class. Next question is, how do you access them? The usual attr_* methods don't work, since they add the methods to the instance level. So, what we could do, is to write the accessors on our own ( by defining methods like self.myvariable and/or self.myvariable= ). But Ruby wouldn't be Ruby if that wouldn't be easier: class Foo class << self; attr_accessor :suits end @suits = ['C', 'D', 'H', 'S'] end The construct "class << self; [...] end" makes all it's contents apply on the class level, not the instance level ( you may have seen it in tutorials you read ). That's all the magic. Of course, you could use @@ as you are doing it currently, but you should be aware of the implications of that. FYI: I think this page ( http://railstips.org/blog/archives/2006/11/18/class-and-instance-variables-in-ruby/ ) gives a really nice explanation of the topic.