TExcelTAD
Home › Ruby › Ruby Duck Typing

Ruby Duck Typing

"If it walks like a duck and quacks like a duck, then it's a duck." Ruby rarely asks what class an object is. It only cares whether the object responds to the methods being called. This style, called duck typing, makes Ruby code flexible and easy to extend.

The idea

ruby · try it yourself
class Duck
  def speak = "Quack"
end

class Robot
  def speak = "Beep boop"
end

class Person
  def initialize(name) = @name = name
  def speak = "Hi, I'm #{@name}"
end

def make_it_talk(thing)
  thing.speak
end

[Duck.new, Robot.new, Person.new("Eli")].each { |t| puts make_it_talk(t) }
Quack
Beep boop
Hi, I'm Eli

Duck, Robot and Person share no parent class and no module. make_it_talk works with all of them simply because each has a speak method. There's no interface declaration — the "interface" is just the method names you call.

Ruby's built-in ducks

The standard library is full of duck typing. puts works with anything that has to_s; << works on strings, arrays and files; anything with each + Enumerable behaves like a collection:

ruby · try it yourself
require "stringio"

def write_report(out)
  out << "Report\n"
  out << "======\n"
  out << "All systems normal\n"
end

buffer = StringIO.new
write_report(buffer)
p buffer.string.lines.size

text = +""
write_report(text)
p text.length

lines = []
write_report(lines)
p lines.size

write_report($stdout)
3
33
3
Report
======
All systems normal

The same method writes to an in-memory buffer, a string, an array and the terminal, because all four understand <<.

Checking with respond_to?

When you must handle different kinds of objects, ask about capabilities, not classes:

ruby · try it yourself
def to_list(value)
  if value.respond_to?(:each)
    value.to_a
  elsif value.nil?
    []
  else
    [value]
  end
end

p to_list([1, 2])
p to_list(1..3)
p to_list({a: 1})
p to_list("solo")
p to_list(nil)
[1, 2]
[1, 2, 3]
[[:a, 1]]
["solo"]
[]
Prefer Over Why
obj.respond_to?(:each) obj.is_a?(Array) accepts ranges, hashes, sets, your own collections
just calling the method checking first simplest; let errors surface
conversion methods (to_s, to_a, Array(x)) type checks normalise input in one step

Conversion protocols

Ruby has two families of conversion methods that act as "duck contracts":

  • Explicit (to_s, to_i, to_a, to_h): "you can be turned into this".
  • Implicit (to_str, to_ary, to_proc, to_hash): "you are basically this" — Ruby calls them automatically.
ruby · try it yourself
class Path
  def initialize(*parts) = @parts = parts
  def to_str = @parts.join("/")    # implicit: acts like a String
end

class Tag
  def initialize(name) = @name = name
  def to_proc = ->(text) { "<#{@name}>#{text}</#{@name}>" }
end

p "root: " + Path.new("usr", "local", "bin")
p ["hi", "bye"].map(&Tag.new("em"))
p Array(nil), Array([1]), Array(1..2), Array("x")
"root: usr/local/bin"
["<em>hi</em>", "<em>bye</em>"]
[]
[1]
[1, 2]
["x"]

String#+ accepts the Path because it has to_str; map(&...) accepts the Tag because it has to_proc.

Duck typing in practice: notifiers

ruby · try it yourself
class EmailNotifier
  def initialize(address) = @address = address
  def deliver(msg) = "email to #{@address}: #{msg}"
end

class SmsNotifier
  def initialize(phone) = @phone = phone
  def deliver(msg) = "sms to #{@phone}: #{msg[0, 20]}"
end

class LogNotifier
  def deliver(msg) = "log: #{msg}"
end

class AlertService
  def initialize(notifiers) = @notifiers = notifiers

  def alert(msg)
    @notifiers.map { |n| n.deliver(msg) }
  end
end

service = AlertService.new([
  EmailNotifier.new("ops@example.com"),
  SmsNotifier.new("+44 7700 900123"),
  LogNotifier.new,
])
puts service.alert("Disk usage above 90 percent")
email to ops@example.com: Disk usage above 90 percent
sms to +44 7700 900123: Disk usage above 90
log: Disk usage above 90 percent

Adding a Slack notifier later means writing one new class with a deliver method — AlertService never changes.

Testing becomes easy

Duck typing makes fakes trivial: any object with the right methods can stand in for the real thing.

ruby · try it yourself
FakeNotifier = Struct.new(:sent) do
  def deliver(msg)
    sent << msg
    "recorded"
  end
end

class AlertService
  def initialize(notifiers) = @notifiers = notifiers
  def alert(msg) = @notifiers.map { |n| n.deliver(msg) }
end

fake = FakeNotifier.new([])
AlertService.new([fake]).alert("test message")
p fake.sent
["test message"]

Note: The trade-off: mistakes show up at run time (NoMethodError) instead of at compile time. Good tests and clear method names are how Ruby developers keep duck-typed code safe.

Test yourself

What does duck typing focus on?

  1. An object's class
  2. Which methods an object responds to
  3. The object's memory size
  4. Declared interfaces

Which check is most in the spirit of duck typing?

  1. x.is_a?(Array)
  2. x.class == Array
  3. x.respond_to?(:each)
  4. Array === x

Why does "a" + obj work when obj defines to_str?

  1. Ruby calls to_s on every object
  2. to_str is an implicit conversion Ruby uses automatically
  3. Strings accept any object
  4. It doesn't work