Last time, I wrote articles about class inheritance and nesting, This time, I will write basic knowledge such as class methods.
As the name implies, it is a method that can be called by a class object.
It cannot be called with an instance object.
Therefore, a common contrast is the instance method
.
This will be discussed later.
There are the following methods for definition.
When using your own class as a receiver in a method, use class name
or self
.
It can be omitted, but self
in the definition cannot be omitted.
class Klass
def self.method_a
new
puts "created Klass instance"
end
end
Klass.method_a
# => created Klass instance
Everything defined during this time is a class method This is convenient when defining multiple items.
class Klass
class << self
def method_a
new
puts "created Klass instance"
end
end
end
Klass.method_a
# => created Klass instance
By the way, you can do it like this in a similar way.
class Klass
end
class << Klass
def method_a
new
puts "created Klass instance"
end
end
Klass.method_a
# => created Klass instance
A method that can be called by an instance object. This is in contrast to the previous class method It cannot be called from a class object.
The definition method is as follows.
class Klass
def method_a
puts "method_a called"
end
def method_b
method_a
puts "method_b called"
end
end
klass_instance = Klass.new
klass_instance.method_b
# => method_a called
# => method_b called
An object-specific method. It can be defined by writing the object name before the method name to be defined. Note that the object must already exist when you define it.
class Klass
end
apple = Klass.new
orenge = Klass.new
def apple.tokui_method
puts "I'm apple"
end
apple.tokui_method
# => I'm apple
orenge.tokui_method
# => undefined method `tokui_method'
If the specified object does not exist when defining it, an error will occur.
class Klass
end
def apple.tokui_method
puts "I'm apple"
end
apple = Klass.new
apple.tokui_method
# => undefined local variable or method `apple' for main:Object (NameError)
Calling super
within a singular method will call the method of the same name defined in the class.
There is also the convenience of being able to override that method.
class Klass
def my_name
puts "I'm fruits"
end
end
apple = Klass.new
orenge = Klass.new
def apple.my_name
super
puts "I'm apple"
end
apple.my_name
# => I'm fruits
# => I'm apple
orenge.my_name
# => I'm fruits