0
0
RubyConceptBeginner · 3 min read

What is Polymorphism in Ruby: Simple Explanation and Example

In Ruby, polymorphism means that different objects can respond to the same method call in their own way. It allows you to write flexible code where the exact behavior depends on the object's class but the method name stays the same.
⚙️

How It Works

Polymorphism in Ruby works by letting different objects share the same method name but perform different actions. Think of it like a universal remote control that can operate many devices—TV, DVD player, or stereo—each responding differently to the same button press.

When you call a method on an object, Ruby looks at the object's class to decide which version of the method to run. This means you can write code that treats different objects the same way, without worrying about their specific types.

💻

Example

This example shows two classes with the same method name speak. Each class defines speak differently, demonstrating polymorphism.

ruby
class Dog
  def speak
    "Woof!"
  end
end

class Cat
  def speak
    "Meow!"
  end
end

def animal_sound(animal)
  puts animal.speak
end

dog = Dog.new
cat = Cat.new

animal_sound(dog)  # Calls Dog's speak
animal_sound(cat)  # Calls Cat's speak
Output
Woof! Meow!
🎯

When to Use

Use polymorphism when you want to write code that works with different types of objects in a uniform way. It helps keep your code clean and easy to extend.

For example, in a game, you might have many character types like players, enemies, and NPCs. Each can have a move method that behaves differently, but your game loop can call move on all characters without special checks.

Key Points

  • Polymorphism means one method name, many behaviors.
  • It relies on Ruby's dynamic method dispatch based on object class.
  • It makes code flexible and easier to maintain.
  • Commonly used with inheritance or duck typing.

Key Takeaways

Polymorphism lets different objects respond uniquely to the same method call.
It enables writing flexible code that works with many object types uniformly.
Ruby decides which method to run based on the object's class at runtime.
Use polymorphism to simplify code and support easy extension.
It is a core concept in object-oriented programming and Ruby's duck typing.