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 .
source share