What is duck-typing?

You often hear Rubyists talking about “duck-typing”

But what is duck typing?

What do ducks have to do with ruby anyway?

In many programming languages, each object, or variable has a static type. By static, we mean it is determined at the time that the code is compiled.

So you define variable s as a String and variable i as an Integer. Function F takes a single parameter and it is defined as only accepting Strings. So if you wrote F(i) the compiler would reject it; you’re trying to pass an Integer to a function that requires a String.

Ruby isn’t static typed, it’s dynamic typed. That means it only tests the types of your objects at run-time, not at compile-time (strictly speaking there isn’t really a compile time for Ruby programs). So you could quite happily pass an integer to your function because the function has no way of telling you what it is expecting.

So what happens if you pass the wrong type of object to a function?

Well, that depends. More likely than not you’ll get an “undefined method” error. Because something has tried to call a method that Strings have that Integers do not.

But what at first glance looks like a weakness is also a strength.

It means that Ruby functions don’t care what they are passed. Take, for example, this function:

You can call add(1, 2) and it will work. You can call add('this', 'that') and it will work.

Because the function doesn’t care what types you pass to it, it only cares that they both understand what to do when added together.

So, it’s a behaviour that can be unnerving, if you’re used to statically typed languages, but also gives you a ton of flexibility.

And why is it called duck typing?

Because, as the saying goes “if it looks like a duck and quacks like a duck it must be a duck”. We don’t care what it is, only how it behaves.

Do you know what to do but not how it works?

Ever wanted to understand why Rails views work the way that they do? Why variables from your controllers are visible inside your views?

Sign up below to get a free 5 part email course on how Ruby on Rails view rendering works and gain a deep understanding of the Rails magic.

We will send you the course, plus the occasional update from this web-site. But no spam, we promise, and it's easy to unsubscribe