0
0
Rubyprogramming~5 mins

Accessing parent methods in Ruby

Choose your learning style9 modes available
Introduction
Sometimes you want to use a method from a parent class inside a child class to keep or extend its behavior.
You want to add extra steps to a method but still keep what the parent method does.
You want to fix or change a small part of a method from the parent class.
You want to reuse code from the parent class without rewriting it.
You want to call the original method after doing something new in the child class.
Syntax
Ruby
super

# or

super(arguments)
Use super inside a child method to call the same method from the parent class.
If you call super without arguments, it sends the same arguments the child method received.
Examples
Calls the parent method greet first, then adds its own message.
Ruby
class Parent
  def greet
    puts "Hello from Parent"
  end
end

class Child < Parent
  def greet
    super
    puts "Hello from Child"
  end
end
Calls the parent add method with arguments and doubles the result.
Ruby
class Parent
  def add(x, y)
    x + y
  end
end

class Child < Parent
  def add(x, y)
    super(x, y) * 2
  end
end
Sample Program
The Dog class calls the Animal's speak method using super and adds "and Bark" to the result.
Ruby
class Animal
  def speak
    "Animal sound"
  end
end

class Dog < Animal
  def speak
    parent_sound = super
    "#{parent_sound} and Bark"
  end
end

dog = Dog.new
puts dog.speak
OutputSuccess
Important Notes
If the parent method needs arguments, pass them explicitly or use super without arguments to forward them automatically.
Using super without parentheses passes all arguments received by the child method.
If you use super() with empty parentheses, it calls the parent method without any arguments.
Summary
Use super to call a parent class method from a child class.
Calling super helps reuse and extend parent behavior.
You can pass arguments to super or let it forward the current ones automatically.