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 Duckdef sound"Quack"endendclass Dogdef sound"Bark"endendclass Catdef sound"Meow"endendclass Animaldef make_sound(animal)puts animal.soundendendanimal = Animal.newanimal.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 Duck
, Cat
, and Dog
classes each implement the same sound
method with slight modifications.
The Animal
class has a make_sound
method that receives an object that it calls the sound
method.
Note: It does not matter how the type of object being passed is passed; what matters is that the object being passed contains the
sound
method.