rubyeigenclass

Implicit context and eigenclasses


I recently found an interesting article on implicit contexts in Ruby, and I found the experience quite mind opening. I understood that Ruby holds a reference not only to self (the default method receiver), but also to the current class (also known as default definee or `klass').

From the article, It should be correct to assume that class definition sets both self and the current class to the class that is being defined; as far as we consider normal method definition (i.e. not using the dot syntax to define singleton methods), in the context of method definition with def, self refers to the receiving object, and the current class isn't changed.

The reason i find safe to not consider the dot syntax for defining is that Ruby also offers an explicit way to open the eigenclass of a class, and the very thing I'm interested is understanding how these two implicit contexts are managed when opening a eigenclass.

Using def with the well known syntax for opening a eigenclass:

class << A
  p self

  def foo
    # ...
  end
end

defines foo as a singleton method of A, i.e. an instance method of its eigenclass (be it A'). This code also prints #<Class:A>, so is it correct to say that the << syntax sets both self and the current class to A'?


Solution

  • Yes it actually opens the block under the control of A'. Also you can say that it works like class_eval of A'.