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
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With