Trusted answers to developer questions

How to implement polymorphism using inheritance 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 allows us to execute different implementations for the same function or method.

Polymorphism helps with code reusability as it enables the use of the same interface for a variety of different implementations.

In Ruby, we can utilize polymorphism through inheritance to ensure that the same method defined in a parent class will have different implementations and outputs once a child classes call it.

Code

class Element # parent class
def symbol
puts "this method returns the symbol of the element"
end
end
class Sodium < Element
def symbol # override the parent method
puts "symbol for Sodium: Na"
end
end
class Copper < Element
def symbol # override the parent method
puts "symbol for Copper: Cu"
end
end
element = Sodium.new
element.symbol
element = Copper.new
element.symbol

Line 22 and Line 26 show the same method being called for different child classes. The output shows that the implementations specific to the child class in question were called. The implementation provided by the parent class for the symbol method was overwritten.

Depending on the object the element variable is referencing, the implementation that belongs to that object will be executed.

RELATED TAGS

ruby
Did you find this helpful?