← Back to Ruby Course | Chapter 9: OOP | Lesson 6 of 7

super

super lets a child class call the parent's version of the same method, like asking a parent how they did it first. You can then add your own part.

In this page:

  1. super
Syntax
ruby
class ChildClass < ParentClass
  def method_name(param)
    super          # or super(param)
    # extra behavior
  end
end

super

super calls the same-named method on the parent class from inside an overriding method, letting you extend rather than fully replace the parent's behavior.

Calling super with no parentheses automatically forwards all the current method's arguments; super() with empty parentheses calls the parent method with no arguments at all. This distinction is a common source of subtle bugs if you're not careful.

Warning:
  • super (no parens) forwards the current arguments automatically.
  • super() (empty parens) calls the parent method with no arguments -- these are not the same.

Example: super

markup
class Animal
  def initialize(name)
    @name = name
  end

  def describe
    puts "I am #{@name}"
  end
end

class Dog < Animal
  def initialize(name)
    super(name)
  end

  def describe
    super
    puts "...and I am a dog"
  end
end

rex = Dog.new("Rex")
rex.describe
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Calling super with no parentheses and expecting no arguments, when it passes the current arguments automatically; use super() for none.
  2. Forgetting super in initialize, so parent's setup is skipped.
  3. Using super in a method that has no parent version, which raises NoMethodError.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.