Ruby is purely object oriented programming language. Any object oriented programming language follows its basic four principles which are:
- Polymorphism
- Encapsulation
- Inheritance
- Abstraction
In this series of articles we are going to understand them one by one with Ruby language.
Let’s start with Polymorphism:
Polymorphism means single method name and multiple implementations. In general it can be achieved by either method overloading or method overriding.
Method overloading means same method name but the arguments of that method will be different in terms of numbers and datatype as well.
Unfortunately Ruby doesn’t support method overloading. so for example if you have two methods with same name and different arguments then the last one or say latest one will be invoked and if you invoke it considering the previous one then it will throw wrong number of arguments error(ArgumentError).
We will see in my another post why Ruby is not supporting method overloading even though it is purely object oriented language.
Method overriding means allowing a subclass to change the implementation of a method which is already provided in its superclass. Subclass overrides the behaviour or implementation of superclass.
So in our last example we achieve polymorphism through method overriding. If you noticed, the method #greetings is invoked and returns different results based on the object type which is invoking it. So run time Ruby decides which #greetings method to call based on the object which invokes it.
Let’s see another small example:
The above example is implementing polymorphism for #lint method. It run time decides which lint method to call based on the object which is invoking it.
Hope you have now better understanding of Ruby polymorphism and how to implement it.
In my next article we will see how Inheritance works with Ruby. So keep following!
To get latest updates and new blogs directly on your email, please subscribe to my newsletter.!
Have a happy coding!