Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

communitycreator
ruby

How to implement polymorphism using inheritance in Ruby

Hamza

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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

communitycreator
ruby

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring