In this section, we will learn what the method overriding is and how to create and use them in Ruby.
Note: we’re assuming you’re already familiar with Inheritance in Ruby.
What is Method Overriding in Ruby?
In inheritance, we know that a child class can call a method of the parent class and use it for its own purposes.
But what if the child class wants to have the same method (same name) but with different body then?
This is where method overriding comes in!
Method overriding is creating the same instance method (the same name) that already exists in a parent class, in the body of a child class!
How to override a method in Ruby?
There’s no special syntax or anything related to method overriding in Ruby, actually!
If there’s a method in a parent class and you want to override it in the body of a child class to create your own body for the method, then simply create a method with the same name and set its body.
Example: overriding a method in Ruby
class A def say_hi puts "This message is coming from the class A" end end class B < A def say_hi puts "This message is coming from the class B" end end class C < B def say_hi puts "This message is coming from the class C" end end cObj = C.new cObj.say_hi cObj.say_hi cObj.say_hi
This message is coming from the class C This message is coming from the class C This message is coming from the class C
How does method overriding works in Ruby?
As you can see, in the body of the class C we’ve overridden the method `say_hi` (both classes A and B also have the same method).
Now, whenever we create an object from the class C and call the `say_hi` method, the say_hi method of the class C will be called.
Note: In Ruby, just using the same name as an instance method in a child class is equal to overriding that method! It doesn’t matter if the parent class has the same method with more or fewer parameters! Just use the same method name in a child class and that’s it. You’ve overridden the method.