Ruby - Class Polymorphism

Introduction

Polymorphism can work with objects of multiple types and classes.

For example, the + method works for adding numbers, joining strings, and adding arrays together.

What + does depends entirely on what type of things you're adding together.

Here's a Ruby interpretation of a common demonstration of polymorphism:

Demo

class Animal 
  attr_accessor :name #  ww w  .j av  a 2 s . com

  def initialize(name) 
    @name = name 
  end 
end 

class Cat < Animal 
  def talk 
    "Meaow!" 
  end 
end 

class Dog < Animal 
  def talk 
    "Woof!" 
  end 
end 

animals = [Cat.new("Flossie"), Dog.new("Clive"), Cat.new("Max")] 
animals.each do |animal| 
  puts animal.talk 
end

Result

Here, you define three classes: an Animal class, and Dog and Cat classes that inherit from Animal.

In the code, you create an array of various animal objects: two Cat objects and a Dog object.

Next, you iterate over each of the animals, and on each loop you place the animal object into the local variable, animal.

Last, you run puts animal.talk for each animal in turn.

As the talk method is defined on both the Cat and Dog class, but with different output, you get the correct output of two "Meaow!"s and two "Woof!"s.