Skip to content
Tutorials Center
My learning

Topics

Lesson 56 of 134 ยท Object-Oriented Ruby

Duck Typing and Polymorphism

Learn duck typing in Ruby - polymorphism without inheritance, respond_to?, interfaces by convention, NoMethodError, composition over inheritance and the null object pattern, with examples.

"If it walks like a duck and quacks like a duck, it is a duck." In Ruby this saying is a programming style: instead of asking an object what it is (its class), you ask what it can do (its methods), or simply call the method and let it work. A method that takes something to print does not need a Printer object; it needs anything that responds to write. A method that loops over a collection does not need an Array; it needs anything with each.

This idea, duck typing, is what makes Ruby code flexible. It gives you polymorphism (many kinds of objects used through one interface) without a shared superclass and without declaring interfaces. In this lesson you will see it in action, learn how to check capabilities when you must, understand the failure mode (NoMethodError), and learn when composition is a better tool than inheritance.

Polymorphism without a common parent

Ruby Unrelated classes with the same method

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

make_noise never mentions Duck, Dog or Robot. It only relies on speak. The three classes have nothing in common except that method, and that is enough. When Rock arrives, the call fails with main.rb:17:in 'Object#make_noise': undefined method 'speak' for an instance of Rock (NoMethodError) (printed after the three good lines). The program tells you precisely what was missing. In a statically typed language you would have declared an interface Speaker up front; in Ruby the "interface" is simply the set of methods the calling code uses.

Why not check the class?

Beginners from other languages often write type checks. They work, but they close the door to every object you did not anticipate.

Ruby Class checks versus duck typing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The strict version rejects a Set even though a Set would have worked fine. The duck version accepts arrays, sets, enumerators, ranges mapped to strings and anything else that provides sum through Enumerable. The more of your methods lean on behavior, the easier they are to reuse and to test with simple stand-ins.

Testing with a stand-in

A great benefit is testing: any object with the right method can replace a real collaborator.

Ruby A fake logger replaces the real one

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Checkout accepts any object that has info. The test version records messages instead of printing them. No framework, no interface keyword, no inheritance. The same trick works for clocks, HTTP clients and databases (Test Doubles).

Asking what an object can do: respond_to?

Sometimes you really must handle several kinds of input. Rather than checking the class, check the capability with respond_to?.

Ruby Accepting several inputs by capability

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Each branch tests for a method, not a class. A StringIO, a real File, a socket and any object you write yourself with a read method all take the first branch. Checking for to_str (the implicit conversion, see to_s, inspect and Conversions) is the right way to ask "is this string-like?". The check respond_to?(:read) honours respond_to_missing?, so it also works with proxies (method_missing and respond_to_missing?).

respond_to? returns false for private methods unless you pass true. It also tells you nothing about the arguments a method takes. Treat it as a hint, not a guarantee, and prefer simply calling the method when failing loudly is acceptable.

"Easier to ask forgiveness": rescue NoMethodError carefully

Ruby programmers often call first and handle failure after, instead of checking beforehand. This avoids race conditions and extra checks. But rescuing NoMethodError is dangerous: it also catches errors from inside the method you called.

Ruby Why rescuing NoMethodError is risky

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The first draw(Widget.new) hides a real bug (inside render, @title was never set, so it is nil) behind the friendly fallback message. The respond_to? version says "nothing to draw" only for objects without render and lets the genuine NoMethodError from the bug through. Use rescue NoMethodError only when you can see a very small call, or inspect e.name and e.receiver to confirm what failed.

Ruby's own protocols

The core library is built on duck-typed protocols. If your class supplies the key method, you gain the whole feature set.

Protocol You provide You get
Enumerable each map, select, sort, min, include?, first, lazy, ...
Comparable <=> <, >, between?, clamp, ==
Conversion to_s, to_str, to_ary, to_proc puts, +, destructuring, & blocks
Case equality === case/when, grep
Stream-like IO read, write, each_line works wherever a file is expected
Callable call .(), usable as a strategy in your own APIs
Ruby Your own class joins the protocols

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The class defines one method, each, and include Enumerable fills in dozens more. return enum_for(:each) unless block makes each without a block return an enumerator, which is what lets each_slice(2) and lazy work on it. Even shows that anything with === can sit in a when clause, and the final lines show a lambda and a custom object used interchangeably because both respond to call. More about this in The Enumerable Module.

Polymorphism and the "template" in inheritance

Duck typing does not replace inheritance; it complements it. Inheritance is still good for a true "is-a" family with shared code. Even there, Ruby code often calls methods the subclass must provide, and raises a clear error if it forgot.

Ruby A base class that demands a method

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

NotImplementedError is the conventional signal for "subclass responsibility". Note that it descends from ScriptError, not StandardError, so a bare rescue does not catch it; the example names it on purpose.

Composition over inheritance

Inheritance ties a class to one parent forever, and the parent's details leak into the child. Composition means giving an object parts that it delegates to. Because parts are duck typed, you can swap them freely at runtime.

Ruby Behavior as a part, not a parent

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

With inheritance you would need SwordHero, BowHero and SpellHero subclasses, and a hero could never change weapons. Here, Hero holds a weapon and asks it to attack. This is the Strategy pattern (Design Patterns), and it is just duck typing. The guideline "prefer composition over inheritance" is explored in Design Principles in Ruby.

The null object

A common source of NoMethodError: undefined method for nil is a missing collaborator represented as nil. Instead of scattering if logger checks, supply an object that has the right interface and does nothing.

Ruby nil crashes, a null object does not (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The default NullLogger keeps the importer's code free of conditionals, and only a deliberate logger: nil produces main.rb:10:in 'block in Importer#run': undefined method 'info' for nil (NoMethodError). The null object is duck typing's answer to defensive programming.

When duck typing hurts

Duck typing has costs, and a good Ruby programmer knows them:

  • Late errors. A wrong object may travel far before it hits a missing method. Validate at the boundary of public APIs, with respond_to?, Array(), Integer() or a clear ArgumentError.
  • Implicit contracts. The "interface" lives in your head. Write down which methods a collaborator needs (in comments, YARD or RBS type signatures) and cover them with tests.
  • Shallow similarity. Two objects might have save methods that mean very different things. Name methods precisely.

Ruby also has optional type tools: RBS files and the Steep or Sorbet type checkers describe interfaces without changing how code runs. Most teams add them only for critical libraries.

Rule of thumb: be liberal in what you accept, strict at the edges. Inside your program, call methods and trust your objects. Where data enters (user input, files, network), convert and validate once.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does duck typing mean in Ruby?

    Ruby code relies on objects' behavior. Any object with the needed methods can be used, regardless of class.
  2. 2. Why is raise TypeError unless items.is_a?(Array) often discouraged?

    Class checks block substitutes. Relying on each, sum and similar methods accepts every compatible object.
  3. 3. What is the risk of rescue NoMethodError around a call?

    A bug inside the called method (such as calling a method on nil) raises the same error, and the rescue swallows it. Prefer respond_to? or a narrow call.
  4. 4. Which single method must a class define so that include Enumerable gives it map, select and sort?

    Enumerable builds all of its methods on each. Comparable is the one that needs <=>.
  5. 5. What is the null object pattern for?

    A null object like NullLogger answers the same methods as the real collaborator and quietly does nothing.

Summary

  • Duck typing: call the methods you need; the class does not matter.
  • It gives polymorphism without a shared parent or declared interfaces.
  • Use respond_to? to test a capability, to_str/to_ary for "is it string-like or array-like", and keep rescue NoMethodError narrow.
  • Core protocols (each, <=>, to_s, ===, call) unlock large parts of the library for your own classes.
  • Prefer composition: hold parts that share an interface and delegate to them.
  • A null object replaces nil checks; validate at the boundaries to get early, clear errors.

Next: Singleton Methods and the Singleton Class