← homeProgramming (Програмування)

What does super do in Ruby?

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 ...

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.

🔥 More posts

All posts
Programming (Програмування)May 23, '23 06:57

What is debugging?

Debugging is the process of identifying, analyzing, and correcting errors or defects in the softw...

Programming (Програмування)Jun 4, '23 21:19

How to clone a GitHub repository?

To clone a repository from GitHub, you will need Git installed on your computer.1. Open the web p...

Computers and technologies (Комп'ютери та технології)Jun 23, '23 12:07

What is Ubuntu? What is it used for?

Ubuntu is a popular distribution of the Linux operating system, based on open-source software. It...