0
0
Rubyprogramming~5 mins

Super keyword behavior in Ruby

Choose your learning style9 modes available
Introduction

The super keyword helps you call a method from a parent class inside a child class. It lets you reuse and extend code easily.

When you want to add extra steps to a method but keep the original behavior.
When you override a method but still need the parent class's version to run.
When you build on top of existing code without rewriting it.
When you want to keep your code organized and avoid duplication.
Syntax
Ruby
super
super()
super(arg1, arg2)

super without parentheses passes all arguments from the current method to the parent method.

super() calls the parent method with no arguments, even if the current method has some.

Examples
This calls the parent greet method with the same argument, then adds a new message.
Ruby
class Parent
  def greet(name)
    puts "Hello, #{name}!"
  end
end

class Child < Parent
  def greet(name)
    super
    puts "Welcome!"
  end
end

Child.new.greet("Alice")
Here, super() calls the parent method with no arguments, even if the child method had some.
Ruby
class Parent
  def greet
    puts "Hello!"
  end
end

class Child < Parent
  def greet
    super()
    puts "Welcome!"
  end
end

Child.new.greet
This calls the parent add method with specific arguments and then doubles the result.
Ruby
class Parent
  def add(a, b)
    a + b
  end
end

class Child < Parent
  def add(a, b)
    result = super(a, b)
    result * 2
  end
end

puts Child.new.add(3, 4)
Sample Program

The Dog class calls the speak method from Animal using super, then adds its own message.

Ruby
class Animal
  def speak(sound)
    puts "Animal says: #{sound}"
  end
end

class Dog < Animal
  def speak(sound)
    super
    puts "Dog wags tail."
  end
end

Dog.new.speak("Woof")
OutputSuccess
Important Notes

If the parent method does not exist, calling super will cause an error.

Using super helps keep code DRY (Don't Repeat Yourself).

Summary

super calls the parent class's method from a child class.

Without parentheses, super passes all current arguments to the parent method.

With empty parentheses super(), it calls the parent method with no arguments.