About singular methods

Introduction

I have summarized Ruby's singular methods and singular classes as a memorandum.

Singular method

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.

The identity of the singular method

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.

Singular 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

About singular methods
About HttpServlet () methods
About Ruby methods
About Ruby instance methods
About calling instance methods
Find out about class methods
About validation methods in JUnit
About naming Rails model methods
About pluck and ids methods
About =
About Java class variables class methods
[Ruby] Singular methods and singular classes
[Ruby] Singular methods and singular classes
About methods often used in devise
About Java static and non-static methods
About the equals () and hashcode () methods
[For our newcomers] About isXXX methods
About method.invoke
About Kotlin
About Hinemos
Java methods
About inheritance
About params
About Docker
About Rails 6
About form_for
About enum
About polymorphism
About Optional
About hashes
About JitPack
About Dockerfile
About this ()
About devise
Java methods
About encapsulation
About Docker
About JAVA_HOME
About active_hash
About static
About exceptions
About scope
Find out about instance methods and self
[Maven] About Maven
About Ruby regular expressions (metacharacters, captures, related methods)