How to implement polymorphism using inheritance in Ruby

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.

Free Resources