Polymorphism
suggest changePolymorphism ("many forms") is the ability of different objects to respond to the same method call with behaviors tailored to their specific types. Because Ruby is a purely object-oriented, dynamically typed language, polymorphism is central to its design.
In Ruby, polymorphism is achieved primarily through three mechanisms:
- Duck Typing (implicit interface adherence)
- Inheritance and Method Overriding
- Module Mixins (
includeandprepend)
1. Duck Typing (The Ruby Way)
The most idiomatic form of polymorphism in Ruby is duck typing: "If it walks like a duck and quacks like a duck, it's a duck."
In statically typed languages, objects must inherit from a common base class or implement an explicit interface. In Ruby, an object needs only to respond to the requested method name with the expected signature and semantics:
class EmailNotifier
def notify(recipient, message)
puts "Sending email to #{recipient}: #{message}"
end
end
class SMSNotifier
def notify(recipient, message)
puts "Sending SMS to #{recipient}: #{message}"
end
end
class SlackNotifier
def notify(recipient, message)
puts "Posting to Slack channel #{recipient}: #{message}"
end
end
# Polymorphic dispatcher
def broadcast_alert(notifiers, recipient, message)
notifiers.each do |notifier|
notifier.notify(recipient, message)
end
end
services = [EmailNotifier.new, SMSNotifier.new, SlackNotifier.new]
broadcast_alert(services, 'engineering-alerts', 'High CPU utilization detected!')
Notice that EmailNotifier, SMSNotifier, and SlackNotifier share no common parent class beyond Object. They are completely decoupled.
2. Polymorphism via Inheritance
Ruby classes can inherit behavior from a superclass and override specific methods to provide specialized behavior:
class PaymentGateway
attr_reader :api_key
def initialize(api_key)
@api_key = api_key
end
def process(amount)
raise NotImplementedError, "#{self.class} must implement #process"
end
end
class StripeGateway < PaymentGateway
def process(amount)
puts "Authorizing $#{amount} via Stripe API token #{@api_key[0..4]}..."
true
end
end
class PayPalGateway < PaymentGateway
def process(amount)
puts "Redirecting to PayPal checkout for $#{amount}..."
true
end
end
# Client code interacts uniformly with any PaymentGateway subclass:
def checkout(gateway, amount)
if gateway.process(amount)
puts "Checkout successful!"
end
end
checkout(StripeGateway.new('sk_live_xyz123'), 49.99)
checkout(PayPalGateway.new('pp_oauth_abc456'), 25.00)
3. Mixin Polymorphism with Modules
Modules enable polymorphic capabilities without class inheritance. By implementing a single contract method, a class gains dozens of polymorphic methods provided by Ruby's standard library modules.
The Comparable Module
Implementing <=> (the spaceship operator) and including Comparable automatically gives your class <, <=, ==, >=, >, and between?:
class Employee
include Comparable
attr_reader :name, :salary
def initialize(name, salary)
@name = name
@salary = salary
end
# Define comparison logic based on salary
def <=>(other)
return nil unless other.is_a?(Employee)
@salary <=> other.salary
end
end
alice = Employee.new('Alice', 95_000)
bob = Employee.new('Bob', 82_000)
puts alice > bob #=> true
puts bob.between?(alice, alice) #=> false
The Enumerable Module
Implementing each and including Enumerable provides standard iteration and querying algorithms (map, select, reject, find, any?, all?):
class Team
include Enumerable
def initialize
@members = []
end
def add_member(name)
@members << name
end
def each(&block)
@members.each(&block)
end
end
team = Team.new
team.add_member('Alice')
team.add_member('Bob')
team.add_member('Charlie')
# Polymorphic methods from Enumerable work out of the box:
puts team.map(&:upcase).inspect #=> ["ALICE", "BOB", "CHARLIE"]
puts team.find { |m| m.start_with?('B') } #=> Bob
Defensive Duck Typing with respond_to?
When accepting arbitrary polymorphic inputs, you can verify if an object implements a specific method dynamically using respond_to?:
def log_payload(source)
if source.respond_to?(:read)
# Stream / File-like object
puts "Reading stream: #{source.read}"
elsif source.respond_to?(:to_s)
puts "Converting to string: #{source.to_s}"
else
puts "Unsupported source"
end
end