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
objof classA. At this point, the ancestor hierarchy ofobj‘s class is:What
class << obj; ... enddoes is that it creates a classBwhose only instance isobj, and puts it in the ancestor hierarchy ofobjso that the ancestor hierarchy of theobj‘s class becomes:If you write
class << self; ... endwithin the context ofTest, then the body of it will be a class whose sole instance isTest. If you define an instance methodhiwithin that body, then that will apply to instances of that class, which isTest. Hence you will be able to doTest.hi.