Ruby - Polymorphism Example

1. Introduction

Polymorphism is a cornerstone of object-oriented programming that enhances code flexibility and readability. In Ruby, polymorphism allows objects of different classes to be treated as objects of a common superclass. This post will delve into the concept of polymorphism in Ruby, illustrating its importance and demonstrating its implementation.

Definition

Polymorphism is derived from two Greek words: "poly" (meaning "many") and "morph" (meaning "form"). In Ruby, it refers to the ability of different classes to respond to the same method call, each in its unique way. This means that objects of different classes can be treated as if they are objects of the same class. This concept is particularly useful when we want to perform the same action on multiple object types.

2. Program Steps

1. Define multiple classes with a common method name.

2. Create objects of these classes.

3. Use these objects in a unified manner, calling the common method on each, demonstrating polymorphism.

3. Code Program

# Define a Bird class with a common method `move` class Bird def move "I can fly!" end end # Define a Fish class with the same method `move` class Fish def move "I can swim!" end end # Define a Horse class with the same method `move` class Horse def move "I can gallop!" end end # Create objects of each class bird = Bird.new fish = Fish.new horse = Horse.new # Display the move capability of each object using polymorphism puts bird.move puts fish.move puts horse.move 

Output:

I can fly! I can swim! I can gallop! 

Explanation:

1. We first define a Bird class with a method named move. This method returns "I can fly!" when called.

2. Similarly, we define a Fish class and a Horse class, each with a move method. However, the response for each class differs based on their natural movement.

3. We then create objects of the Bird, Fish, and Horse classes.

4. Despite these objects being of different classes, we can call the move method on each, demonstrating polymorphism. Each object responds to the move method in its unique way.

The beauty of polymorphism lies in its ability to simplify code and improve flexibility, allowing objects of different types to be treated uniformly.


Comments