0
0
RubyHow-ToBeginner · 3 min read

How to Use super in Ruby: Simple Guide with Examples

In Ruby, super calls the same method from the parent class, allowing you to extend or reuse its behavior. You can use super with or without arguments to pass the current method's arguments or specify new ones explicitly.
📐

Syntax

The super keyword is used inside a method to call the same method from the parent class. You can use it in three ways:

  • super - calls the parent method with the same arguments received.
  • super() - calls the parent method with no arguments.
  • super(arg1, arg2) - calls the parent method with specific arguments.
ruby
class Parent
  def greet(name)
    "Hello, #{name}!"
  end
end

class Child < Parent
  def greet(name)
    super
  end
end
💻

Example

This example shows how super calls the parent method and adds extra behavior in the child class.

ruby
class Parent
  def greet(name)
    "Hello, #{name}!"
  end
end

class Child < Parent
  def greet(name)
    parent_greeting = super
    "#{parent_greeting} Welcome to Ruby programming."
  end
end

child = Child.new
puts child.greet("Alice")
Output
Hello, Alice! Welcome to Ruby programming.
⚠️

Common Pitfalls

One common mistake is forgetting that super without parentheses passes all arguments automatically, which can cause errors if the parent method expects none or different arguments. Another pitfall is using super() when you want to pass arguments, which sends none instead.

Always check the parent method's parameters to use super correctly.

ruby
class Parent
  def greet
    "Hello from parent"
  end
end

class Child < Parent
  def greet(name)
    # Wrong: super() passes no arguments, but parent expects none
    # This will cause an ArgumentError if parent expects arguments
    super(name)
  end
end

# Correct usage:
class ChildCorrect < Parent
  def greet
    super
  end
end
📊

Quick Reference

UsageDescription
superCalls parent method with current arguments
super()Calls parent method with no arguments
super(arg1, arg2)Calls parent method with specified arguments

Key Takeaways

Use super to call the parent class method with the same arguments.
Use super() to call the parent method without any arguments.
Specify arguments in super(arg1, arg2) to control what is passed.
Check parent method parameters to avoid argument errors with super.
Using super helps extend or reuse parent class behavior cleanly.