← Back to Tutorials
interview6/8/2025

Ruby & Duck Typing

Third article in the Prepare for a Ruby job interview series. In this article, we will see what is Duck Typing.

Duck Typing is a funny notion you should know about. As James Whitcomb Riley said it :

When I see a bird that walks like a duck and swims like a duck and quacks like a duck, I call that bird a duck.

Rather than having to check that an object is of a specific type, all we are concerned about is that the object can answer to a method call in a specific context. So if we have the following :

class Document
  def initialize
  end

  def print
    raise NotImplementedError, 'You must implement the print method'
  end
end

–-

class XmlDocument < Document
  def print
    p 'Print from XmlDocument'
  end
end

–-

class HtmlDocument < Document
  def print
    p 'Print from HtmlDocument'
  end
end

--

class Printer
  def initialize(document)
    @document = document
  end

  def print
    @document.print
  end
end

Then we can give the Printer class any object that answer to the print method.

Printer.new(XmlDocument.new).print
Printer.new(HtmlDocument.new).print

Et voila, that's Duck Typing ! Both the Xml and Html documents act like printable documents by responding to the print method.

Continue to the fourth part about the mysterious Include and Extend.

Comments

Loading comments...

Level Up Your Dev Skills & Income šŸ’°šŸ’»

Learn how to sharpen your programming skills, monetize your expertise, and build a future-proof career — through freelancing, SaaS, digital products, or high-paying jobs.

Join 3,000+ developers learning how to earn more, improve their skills, and future-proof their careers.

Ruby & Duck Typing | Devmystify