What is << in this context?

I am 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 use syntax that I am not familiar with. Please see use <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 does class << self mean? It has a corresponding end block, but I still don't quite understand what exactly this does

(Note: The point of the above exercise simply shows that you cannot create a metaclass, which, as I understand it, I'm just having problems wrapping my head around this <<operator in this context.

Thanks!

+4
source share
1 answer

class << self opens the self singleton class, so methods can be overridden for the current self object.

Let's look at a specific example:

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

Let's take a closer look at what's happening here:

  • Inside the metaclass definition, self refers to the current instance, in this example the string "abc".
  • class << self in this example is equivalent to class << "abc" , which opens the singleton class of this instance, in this case String "abc".
  • Then it returns self inside the open class of the current instance - the open class is in the String class example.

In general, a metaclass definition opens a class definition for a given instance / object, and then returns that class name.

A more detailed look at the "I" can be found in Yehuda Katz's article "Metaprogramming in Ruby: All About Me . "

I also recommend a series of screens with the help of Pragmatic programmers on the Ruby object model and metaprogramming .

+2
source

All Articles