Polymorphism is an important concept in object-oriented programming. It allows us to implement many different implementations of the same method, helping with code reusability and avoiding redundancy.
In Ruby, we can implement polymorphism using inheritance or duck typing. Although we can utilize method overriding to implement polymorphism using inheritance, we use a different approach for duck typing.
To implement polymorphism using duck typing, we focus on modifying an object’s operations and calling those operations by switching the objects at runtime without checking which object actually invokes the operation or method.
The core idea is to separate the type of class from its methods.
If it looks like a duck, swims like a duck, and quacks like a duck, then it probably is a duck.
class Duck def sound "Quack" end end class Dog def sound "Bark" end end class Cat def sound "Meow" end end class Animal def make_sound(animal) puts animal.sound end end animal = Animal.new animal.make_sound(Duck.new) animal.make_sound(Dog.new) animal.make_sound(Cat.new)
The example shows an implementation of the duck typing approach for polymorphism. The
Dog classes each implement the same
sound method with slight modifications.
Animal class has a
make_sound method that receives an object that it calls the
Note: It does not matter how the type of object being passed is passed; what matters is that the object being passed contains the