I have summarized Ruby's singular methods and singular classes as a memorandum.
In Ruby, you can define a method that is unique to an object directly, and that method is called a singular method.
class Hoge
end
obj = Hoge.new
def obj.method1
p 'Singular method'
end
obj.method1
# => "Singular method"
You should be able to confirm that method1
was called in this way.
So what are the consequences of another object?
obj2 = Hoge.new
obj2.method1
# => undefined method `method1'
I got an error like this. You can see that it is a method unique to ʻobj` even in the same class.
You can see that you can't call a method if it's an object that doesn't define a singular method even in the same class. To be on the safe side, let's use singleton_methods
to make sure that the Hoge
class doesn't really have any singular classes.
class Hoge
end
obj = Hoge.new
def obj.method1
p 'Singular method'
end
p Hoge.singleton_methods
p obj.singleton_methods
# => []
# => [:method1]
However, if a method belongs to a class, you may be starting to wonder which class the singular method belongs to. As a result of investigation, it seems that there is a ** singular class ** and the singular method belongs to that class.
To be honest, I only understand that singular classes define singular methods. Let's check the contents using ʻancestors`.
p obj.singleton_class.ancestors
# => [#<Class:#<Hoge:0x00007fca5c866ab8>>, Hoge, Object, Kernel, BasicObject]
As you can see, the superclass of the singular class is like your own class. The method search seems to be in the order of singular class → own class → superclass ....
Recommended Posts