'class << ' merely changes the self

anand posted this on 15 Apr 2011

Many ruby programmers use class << self inside some class definition to create class methods. But the actual meaning behind this class << self is completely different. Using it for creating class methods is just one usecase.

class << soomeobject, actually changes 'self' object inside a definition block. In ruby, in any place there is something called as current object or 'self'. If you are calling a method and if you don't specify a receiver or object on which the method has to be called (like someobject.methodname() ), the method will be called on 'self' or current object inside that scope.

  1. Inside Instance methods, self is "the object instantiated from the corresponding class".
  2. Inside class methods and class definitions, self is the "the class object".
  3. Inside Module methods, self is either the "instance of the class that includes it" or "object that extends itself with the module".
  4. Inside Module definition, outside of module methods, self is "the module object".
So like this, in every scope, self changes itself. If you want to enforce self to be a particular object in particular place in your program, you use class << self. Here are some self-explanatory code snippets that demonstrates this.

And now comes more familiar way of using class << self.

And there is nothing called as class methods. Classes are pure ruby objects. Going by that logic, class methods are nothing but instance methods of singleton class of an object(saying it differently, singleton methods)