What does the super keyword do in Ruby?
It calls a method on the parent class with the same name as the method that calls super
.
For example:
If you call a method named i_like_chocolate
, and then you call super
within that method, Ruby will try to find another method with that same name on the parent class of whoever owns this method.
This keeps bubbling up through the class ancestry chain like a regular method call.
If the method doesn’t exist it will trigger a NoMethodError
exception, and if a method_missing
is found it will use that.
Now:
Let’s take a look at some code examples!
Super Without Arguments
In the following example we have a Cat
class that inherits from Animal
.
The Cat
class has a name
method that uses super
to call the same method on its parent class (Animal
).
Here’s the code:
class Animal def name puts "Animal" end end class Cat < Animal def name super end end cat = Cat.new cat.name # "Animal"
The Ruby super keyword behaves differently when used with or without arguments.
Without arguments:
It will pass along the arguments used for the original method call to the new one, including keyword arguments & a block if given.
Here's an example:
def puts(*) super end puts 1, 2, 3
This method, defined outside of any class, will belong to Object
. This means it will be called before the original puts
method.
Now:
When you call puts
you're calling this new method we have created which then uses super
to call the original puts
.
When to Use Super vs Super()
We just looked at how to use super
for calling parent methods.
But what if the parent method doesn't take the same number of arguments?
In that case you can use:
super()
for no argumentssuper(arg1, arg2, ...)
to choose what arguments you want to pass
Example:
def puts super() end
Notice how the parenthesis have special meaning here, unlike a regular method call.
A few more things to know about super
:
- It can only be used inside a method
- It returns the result from calling the parent method
- It can be called multiple times
The bolded line (super
returns results) is key to understanding some of the uses for super
that you may find in the wild.
You can use super
to implement the decorator pattern, or if you call it inside the initialize
method it can be used to initialize instance variables on the parent class.
Summary
You've learned about the Ruby super keyword, what it is & how it works in different situations!
If you enjoyed this article you may want to subscribe to the RubyGuides newsletter to get more content like this & other useful Ruby tips only available to subscribers.