+ 1
Problem Ruby super inheritance
Hi, I was learning the Inheritance lesson of Ruby when I came to the super explanation. In one example there is this code wihich works good https://code.sololearn.com/1073/#rb I tried to extend it with one more parameter (size) https://code.sololearn.com/cinu9MTw1Qw2/#rb to test some things when I came up with an error because of the parameters of the base class. I do not understand that error. I just keep the same structure as the example. In both of them the base class has less parameters than the constructor needs, but I only received the error in the second one. Can anyone tell me why?
2 ответов
+ 2
When ruby constructs Cat it also has to construct Animal, which it inherits from.
But Animal needs some arguments passed to it to be constructed, which is what super is for, it passes the arguments to the constructor( the initializer ) for Animal.
In your first example Animal only needs to know about a name.
In the Cat's constructor super(name) passes the name to the Animal's constructor.
However in your 2nd example, Animal needs to know about a name and a size.
But in the Cat's constructor you have only super. Which is not passing 2 arguments to the Animal's constructor.
I believe if super is left without arguments it passes all, 3 in this case, parameters to Animal.
So, Animal cannot be constructed and in turn Cat cannot be constructed.
To fix it use super to pass name and size to the Animal's constructor.
super(name,size)
0
Of course. I have completely missunderstood the meaning of super in the constructor and with parameters comparing with just super in a function.
Now it is everything clear, and of course you are right! Thank you very much!