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.
class Element # parent classdef symbolputs "this method returns the symbol of the element"endendclass Sodium < Elementdef symbol # override the parent methodputs "symbol for Sodium: Na"endendclass Copper < Elementdef symbol # override the parent methodputs "symbol for Copper: Cu"endendelement = Sodium.newelement.symbolelement = Copper.newelement.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.