Question

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'?

Was it helpful?

Solution

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

OTHER TIPS

Actually, what you wrote is exactly the same as writing:

class A
  class << self
    def foo
      #...
    end
  end
end

the class << self syntax indicates that a block of definitions will follow, and this is going to go straight to the eigenclass of the object passed to <<. And yes, I said Object, not Class. Try this (provided the class definition above):

a = A.new
class << a
  def foo2
  end
end
a.singleton_methods
b = A.new
b.singleton_methods

this means, in this case, you are defining the method foo2 in the eigenclass of the object a. But this is the eigenclass of the object itself, not the class. So, further objects of the same class will not share this foo2 definition.

So what this means? Ruby is (or claims to be) a pure OO language. Everything is an object. An Object of a class defined by you is an Object. A Class defined by you is also an Object. Of type Class. Which inherits from Object. In Ruby, all objects have an eigenclass. Actually, the definition of "class methods" is just an interpretation of its concept. "Class Methods" are not really class methods, but methods defined in the eigenclass of the class. So, when you are calling a "class method", you are indeed calling an object method. This object just happens to be a class you defined. How you define eigenclass methods? Exactly the class << self syntax. The "self" in this context is whatever you passed as an argument to class <<.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top