Trusted answers to developer questions

How to implement polymorphism using duck-typing in Ruby

Free System Design Interview Course

Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2024 with this popular free course.

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.

The variable 'animal' calls the same method despite different objects implementing them
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 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.

RELATED TAGS

ruby
Did you find this helpful?