The super keyword in Ruby
In this article we’re going to explore the following topics:
- implicit arguments
super
vssuper()
super
with blockssuper
with the ancestors chain
implicit arguments
When a method with arguments is overridden by one of its child classes then a call to super
without any argument in the child method will automatically pass the arguments of the child method to the parent method.
Let’s have a look to the following example
Here the Child
class inherits from the Parent
class.
The Child
class overrides the Parent#say
method.
Within the Child#say
method, we call super
without any argument.
So, Ruby tries to find a method #say
in the ancestor chain
of the Child
class.
Then it passes the message
argument to the freshly found method.
NB: feel free to have a look to my article if you’re unfamiliar with the
Ancestors Chain
mechanism in Ruby.
But, what if the Parent#say
method doesn’t expect any argument ?
super vs super()
Let’s redefine the Parent#say
method by removing the message
argument
An ArgumentError
is raised because the Parent#say
method doesn’t expect any argument.
In effect, the call to super
in the Child#say
method implicitly passes the message
argument from the Child#say
method to the Parent#say
method.
To avoid this problem, we can explicitly indicate to super
not to take any argument from the Child#say
method.
To do so, we can add parentheses to the super
keyword — super()
So let’s try to pass a block to our Parent#say
method.
super with blocks
Let’s redefine the Parent#say
method by adding a yield
keyword in it
The block passed to the Child.new.say
method is implicitly passed to the Parent#say
method through the super
keyword.
Then we use the yield
keyword to catch the block and execute it in the Parent#say
method.
NB: feel free to have a look to The yield keyword article if you’re unfamiliar with the
yield
keyword.
super with the ancestor chain
Let’s make the Parent
class inherit from the GrandParent
class — which defines the #say
method
Here we can see that the super
keyword tries to find the #say
method in the Parent
class.
The Parent
class doesn’t define this method.
So super
tries to find the #say
method in the superclass of the Parent
class — the GrandParent
class.
The GrandParent
class defines the #say
method.
So, The 'Hi Rubyist!'
argument passed to the Child.new.say
method call is implicitly passed to the GrandParent#say
method through the super
keyword.
Ruby Mastery
We’re currently finalizing our first online course: Ruby Mastery.
Join the list for an exclusive release alert! 🔔
Also, you can follow us on x.com as we’re very active on this platform. Indeed, we post elaborate code examples every day.
💚