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
.