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:
def add first, second
first + second
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.