This content has been automatically translated from Ukrainian.
Ruby has the keyword "super"is used to call the parent method from a subclass. When you declare a subclass, it inherits all the methods of the parent class. In some cases, you may need to replace the functionality of the parent method, but still want to call it to save some logic. Here the keyword "super" comes to the rescue.
Here is an example that demonstrates the use of "super" in Ruby:
class Parent
def say_hello
puts "Hello from the Parent class!"
end
end
class Child < Parent
def say_hello
puts "Hello from the Child class!"
super # We call the parent method
end
end
child = Child.new
child.say_hello
In this example, there are two classes: "Parent" (parent) and "Child" (subclass). The "Child" class inherits the "say_hello" method from the "Parent" class. In the "say_hello" method of the "Child" class, we first output the string "Hello from the Child class!" and then call "super", which will call the "say_hello" method from the parent class.
As a result, when we instantiate the "Child" class and call the "say_hello" method, we get the following result:
Hello from the Child class! Hello from the Parent class!
Thus, the use of "super"allows us to add functionality (extend functionality) to subclass methods while maintaining parent class logic.
This post doesn't have any additions from the author yet.