Ruby's super keyword
The super
keyword in Ruby is used to invoke a method with the same name as the one currently being executed in the superclass. It allows us to extend or modify the behavior of a method defined in a superclass without completely overriding it. The super
keyword is typically used within a subclass to call the superclass's implementation of the method.
Let's consider an example to understand the usage of the super
keyword:
class Vehicle
def start_engine
puts "Engine started!"
end
end
class Car < Vehicle
def start_engine
puts "Car started!"
super
end
end
my_car = Car.new
my_car.start_engine
In this example, we have a Vehicle
class with a start_engine
method. The Car
class inherits from Vehicle
and overrides the start_engine
method. Within the overridden method in the Car
class, we call super
to invoke the superclass's implementation of start_engine
. This allows us to extend the behavior while still retaining the original functionality.
When we execute the code, the output will be:
Car started!
Engine started!
Here, the start_engine
method in the Car
class prints "Car started!" and then calls super
, which invokes the start_engine
method in the Vehicle
class. The superclass's implementation prints "Engine started!".
The super
keyword can also take arguments when necessary. Let's consider another example:
class Animal
def make_sound(sound)
puts sound
end
end
class Dog < Animal
def make_sound(sound)
puts "Bark!"
super("Woof!") # Passes "Woof!" as an argument to super
end
end
my_dog = Dog.new
my_dog.make_sound("Woof woof!")
Output:
Bark!
Woof!
In this example, the make_sound
method in the Dog
class calls super("Woof!")
, passing the argument "Woof!" to the make_sound
method in the Animal
class. The superclass's implementation prints "Woof!".
The super
keyword is useful when we want to add behavior to a method while still utilizing the functionality provided by the superclass. It promotes code reuse and follows the principle of Don't Repeat Yourself (DRY).
Additionally, it's worth noting that the super
keyword can be used without parentheses, like super
or with parentheses, like super()
. The choice depends on whether arguments need to be passed to the superclass method.
Last updated