ruby: class instance variables vs instance variables

it was very confusing for me to find out that @variable may mean 2 very different things.

No, it doesn’t. Classes are objects just like any other object. They can have instance variables just like any other object. They can have instance methods just like any other object. In fact, unlike Java, which has three different kinds of “methods” (instance methods, static methods and constructors), in Ruby, there is exactly one kind of method: instance methods.

The beauty of having classes being objects is precisely that @variable always means exactly the same thing.

There is no such thing as a class instance variable: it’s just a normal instance variable like any other. The object happens to be an instance of Class, but that doesn’t change the nature of the instance variable. An instance variable of an object of class String is not a string instance variable, it’s just an instance variable. Likewise, an instance variable of an object of class Class is just an instance variable.

There is no such thing as a class method: it’s just a normal singleton method of an object which happens to be an instance of Class. (Acually, there’s no such thing as a singleton method either: it’s just a normal instance method of the object’s singleton class.)

Note: Rubyists may use the term “class method” in casual conversation. But that doesn’t mean that class methods actually exist, it only means that “instance method of the class object’s singleton class” is a mouthful. The important thing is: because classes are objects, they work exactly like all other objects. They can have instance methods (defined in class Class or inherited from Module, Object, Kernel or BasicObject), they can have “singleton methods” (which really are instance methods of their respective singleton classes), they can have instance variables.

They can also have class variables (@@variables) … those are weird. Ignore them 🙂

Leave a Comment