'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.
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)
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.
- Inside Instance methods, self is "the object instantiated from the corresponding class".
- Inside class methods and class definitions, self is the "the class object".
- Inside Module methods, self is either the "instance of the class that includes it" or "object that extends itself with the module".
- Inside Module definition, outside of module methods, self is "the module object".
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)
~