Polymorphism is a fundamental concept in object-oriented programming, and Ruby embraces it fully. It allows objects of different classes to respond to the same method call, providing flexibility and extensibility in code design.
The term "polymorphism" comes from Greek, meaning "many forms." In Ruby, it refers to the ability of different objects to respond to the same method name, each in its own way. This concept is crucial for writing flexible and reusable code.
Ruby uses duck typing, a form of polymorphism where the class of an object is less important than the methods it defines. "If it walks like a duck and quacks like a duck, it's a duck."
def make_sound(animal)
animal.speak
end
class Dog
def speak
"Woof!"
end
end
class Cat
def speak
"Meow!"
end
end
dog = Dog.new
cat = Cat.new
puts make_sound(dog) # Output: Woof!
puts make_sound(cat) # Output: Meow!
In this example, make_sound
works with any object that responds to the speak
method, regardless of its class.
This type of polymorphism is achieved through Ruby Inheritance. Subclasses can override methods defined in their superclass, allowing for different implementations of the same method name.
class Animal
def move
"I'm moving!"
end
end
class Fish < Animal
def move
"I'm swimming!"
end
end
class Bird < Animal
def move
"I'm flying!"
end
end
animals = [Animal.new, Fish.new, Bird.new]
animals.each { |animal| puts animal.move }
# Output:
# I'm moving!
# I'm swimming!
# I'm flying!
Polymorphism is a powerful feature in Ruby that enhances code flexibility and reusability. By understanding and applying polymorphic principles, developers can create more maintainable and extensible Ruby applications. Whether through duck typing or inheritance, polymorphism is an essential tool in the Ruby programmer's toolkit.