Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does class << self mean?

Regarding:

class Test
  class << self
    def hi
      puts "Hi there"
    end
end

I came up with following image in my head:

Since everything is an object in Ruby, classes themselves are objects of class Class. By calling class << self you open up Class definition from the inside of Test and inject few instance methods. Since Test is an instance of Class, you can call those methods same way you call instance methods on your objects: Test.hi.

Following is the pseudo code which helps to visualise my previous sentence:

class Class
    def hi
        puts “Hi there”
    end
end

Test = Class.new(class Test
end)
Test.hi

Am I getting this right?

like image 269
spacemonkey Avatar asked Feb 17 '13 20:02

spacemonkey


1 Answers

Suppose we have an object obj of class A. At this point, the ancestor hierarchy of obj's class is:

[A, ...]

What class << obj; ... end does is that it creates a class B whose only instance is obj, and puts it in the ancestor hierarchy of obj so that the ancestor hierarchy of the obj's class becomes:

[B, A, ...]

If you write class << self; ... end within the context of Test, then the body of it will be a class whose sole instance is Test. If you define an instance method hi within that body, then that will apply to instances of that class, which is Test. Hence you will be able to do Test.hi.

like image 175
sawa Avatar answered Sep 29 '22 02:09

sawa