Polymorphism in Ruby

Katerina
2 min readMay 2, 2017

--

Polymorphism comes from the greek word Poly (meaning many) and morphē (meaning forms) aka many forms.

In programming, polymorphism is the idea of different objects using the same method but behaving differently.

This idea stops methods becoming too specific with multiple if and elsif conditional statements and instead encourages the idea of making methods that are more simple so they only do one thing. Methods like this are known as single responsibility methods.

There are different ways to use polymorphism. Inheritance between classes and Duck Typing are the two ways I have seen referenced most frequently. Below is an example of Duck Typing where you can see how different objects respond to the same message; each object has it’s own response even though the method each object is using is the same.

class Country  def say_hello(country)
country.say_hello
end
def typical_dish(country)
country.typical_dish
end
endclass Italy def say_hello
"Ciao!"
end
def typical_dish
"Risotto"
end
endclass Spain def say_hello
"Hola"
end
def typical_dish
"Paella"
end
end--------------------In the command line:country = Country.new
italy = Italy.new
puts country.say_hello(italy) # Ciao!
puts country.typical_dish(italy) # Risotto
spain = Spain.new
puts country.say_hello(spain) # Hola
puts country.typical_dish(spain) # Paella

In the example above, we can see a class called Country which has the methods say_hello(country) and typical_dish(country). I create two new Classes — Italy and Spain — and define the same methods inside of them.

I then create new instances of Country and Italy and save the new instance of Italy in a variable called ‘italy’ and Country in a variable called ‘country’. I use the italy variable as my argument for Country’s say_hello method. Essentially, this means that when I call say_hello on italy, because it knows the say_hello method, it uses the information inside its method and “Ciao” is returned.

When I create and pass in a new instance of the Spain class to Country’s say_hello method, although the variable spain has the same method, the information inside the method is different so “Hola” is returned instead.

This is a small introduction into how Polymorphism works. Used correctly, it could help make your code more manageable and flexible as methods are not tied to only one object.

--

--