This content has been automatically translated from Ukrainian.
In Ruby, the keyword "super" is used to call a 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 override the functionality of the parent method, but still want to call it to preserve certain logic. This is where the keyword "super" comes in handy.
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 # Calling the parent method
end
end
child = Child.new
child.say_hello
In this example, there are two classes: "Parent" (the parent) and "Child" (the 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 invoke the "say_hello" method from the parent class.
As a result, when we create an instance of the "Child" class and call the "say_hello" method, we get the following output:
Hello from the Child class! Hello from the Parent class!
Thus, using "super" allows us to add functionality (extend functionality) in the subclass methods while preserving the logic of the parent class.
This post doesn't have any additions from the author yet.