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

super

In this page:

  1. super

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
🔒

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.