Rails Insights

What Does the Super Keyword Do in Ruby?

When working with object-oriented programming in Ruby, you may come across the super keyword. This keyword plays a crucial role in inheritance and method overriding in Ruby. In this article, we will explore what the super keyword does and how it can be used in your Ruby code.

Understanding Inheritance in Ruby

Before diving into the specifics of the super keyword, it's important to understand the concept of inheritance in Ruby. Inheritance allows a class to inherit attributes and behaviors from another class, known as the superclass. This promotes code reusability and helps in organizing code in a hierarchical manner.

Using the Super Keyword

The super keyword is used to call the superclass's implementation of a method. This is particularly useful when you want to extend the functionality of a method defined in the superclass without completely overriding it. By calling super within a method, you can execute the superclass's implementation before or after adding your own custom logic.

class Animal
  def speak
    puts "Animal speaks"
  end
end

class Dog < Animal
  def speak
    super
    puts "Dog barks"
  end
end

dog = Dog.new
dog.speak

In the example above, the Dog class inherits from the Animal class and overrides the speak method. By calling super within the speak method of the Dog class, the Animal class's speak method is executed before the custom logic of barking is added.

Passing Arguments with Super

You can also pass arguments to the superclass's method using the super keyword. This allows you to customize the behavior of the superclass's method based on the arguments passed from the subclass.

class Vehicle
  def initialize(color)
    @color = color
  end
end

class Car < Vehicle
  def initialize(color, brand)
    super(color)
    @brand = brand
  end
end

car = Car.new("red", "Toyota")

In this example, the Car class calls super(color) to pass the color argument to the Vehicle class's initialize method. This allows the Car class to set the color attribute before initializing its own brand attribute.

Conclusion

The super keyword in Ruby is a powerful tool for working with inheritance and method overriding. By calling super within a method, you can leverage the functionality of the superclass while adding your own custom logic. Understanding how to use the super keyword effectively will help you write more maintainable and organized Ruby code.

Published: May 30, 2024

© 2024 RailsInsights. All rights reserved.