Full Stack Founder · a live cohort for developersjoin the waitlist →
← Back to Blog
interviewThibault “Tibo” Denizet

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 .

$ whoami

Tibo, creator of Devmystify

Tibo

Hi, I'm the creator of Devmystify and author of Modular Rails and Master Ruby Web APIs.

I built a 6-figure consulting business while living in Thailand and now share practical advice on turning dev skills into a business: consulting, digital products, and SaaS.

join the cohort waitlist →

Comments

Loading comments...

> one email a week, real numbers

The other half of the job

You can already build. The free ebook answers the rest: which business is right for you, the real numbers behind each path, and the ladder to climb without quitting your job.

join 2,700+ developers · unsubscribe anytime · no spam, only receipts

Ruby & Duck Typing | Devmystify