super cat with super() power !!

In this article we’re going to explore the following topics:

implicit arguments

super vs super()

vs super with blocks

with blocks super with the ancestors chain

Before to start

I’m thrilled to share with you our latest project: Fun Facts about Ruby — Volume 1

Please feel free to spread the word and share this link! 🙏

Thank you for your time!

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 to don’t 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 ancestors 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.

Voilà!

ONE MORE THING ⬇

Feel free to subscribe here: www.rubycademy.com