4

I'm working on this tutorial here: http://rubymonk.com/learning/books/4-ruby-primer-ascent/chapters/39-ruby-s-object-model/lessons/131-singleton-methods-and-metaclasses

The lesson is on classes/metaclasses, but they are using a syntax that I'm not familiar with. Please see the use of << below

class Object
  def metaclass
    class << self
      self
    end
  end
end


a=Object.new
p a.metaclass.new

I know def metaclass is a method, but what is meant by class << self? It has a corresponding end block, but I'm still very unclear what this is exactly doing

(Note: The point of the above exercise is just showing that you cannot instantiate a metaclass -- which I understand, I'm just having trouble wrapping my head around that << operator in this context.

Thanks!

Ricky
  • 2,850
  • 5
  • 28
  • 41

1 Answers1

2

class << self opens up self's singleton class, so that methods can be redefined for the current self object.

Let's look at a particular example:

 s = String.new("abc")
 s.metaclass
   => "#<Class:#<String:0x0000010117e5d8>>" 

Let's have a closer look at what happens here:

  • Inside the definition of metaclass, self refers to the current instance, in this example the string "abc".
  • class << self in this example is equivalent to class << "abc" which opens up the singleton-class of that given instance , in this case String "abc".
  • It then returns self inside the opened-up class of the current instance -- the opened-up class is in the example the class String.

In general, the definition of metaclass opens up the class definition of the class of the given instance/object, and then returns that class name.

A more detailed look at 'self' can be found in Yehuda Katz's article "Metaprogramming in Ruby: It’s All About the Self".

I also recommend the screen-cast series by the Pragmatic Programmers on The Ruby Object Model and Metaprogramming.

Tilo
  • 33,354
  • 5
  • 79
  • 106