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?


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

链接地址: http://www.djcxy.com/p/69508.html

上一篇: UIView背景渐变与界面生成器视图

下一篇: 类“自我”是什么意思?