What's the fuzz about ducktyping?

Even if you’re not new to ruby, the concept of ducktyping might evokes something vague and unclear to you. I personally had to re-read the dedicated section of my ruby book a couple of times before I finally grasped the concept.

What is ducktyping?

Ducktyping is the art of judging an object on what it can do rather than on what it is believed to be. What it means is that an object doesn’t live and die with a label pinned on it’s forehead. In ruby, an object can do anything it is able to do, isn’t it great? Yeah, it is.

It makes a lot of sense when you think about it. Suppose you have a method called be_scary that accepts one parameter representing a lion that will roar at the call of the roar! method.

def be_scary(the_lion)
  the_lion.roar!
end

Even if the creator of this method seemed to have forget it, there are a lot of other living creatures on the earth that can express their might like that. No need to remind the programmer about that however, because we can use ducktyping to pass any scary stuff to our method. The thing that I will pass to the be_scary method do not need to share anything in common with a lion excepts for the fact that it can roar. Imagine for a second that scientists just discovered that rabbits could roar in some very specific conditions. No worries! You don’t have to touch a single line of your ruby program structure. Just pass the rabbit instance to the be_scary method and the interpreter will try to find it’s roar! method. Ruby doesn’t play a bouncer role like in many other languages. It doesn’t stand at the method gates while refusing the entrance to objects who are not exactly what the method is expecting to see. Instead, the ruby interpreter slacks off and let everyone enters into the method so they can try their luck with the roar! method.

Isn’t it the same thing than dynamic typing?

No, dynamic typing just makes reference to the way the type(or class) of an object is determined, that is, when you’ll start putting stuff in it. Ducktyping picks up from there and extends the capabilities. Generally, when ducktyping occurs, the interpreter knows the type of an object but still won’t exert authority on it by prohibiting it to enter some methods. We could say that a ducktyped language is always a dynamically typed language but not the other way around. A dynamically typed but not ducktyped language could still refuse objects based on their type at the doors of a method.

If you really want to catch exceptions before the ruby interpreter…

If you don’t feel comfortable with the fact that there is no bouncer at the doors of your method, you’ll be happy to know the existence of the respond_to? method. It kinds of fill the role of the typeof keyword in some other languages. However, instead of verifying if the object is a specific thing, you verify that it can do a specific thing.
See how we could have implemented our be_scary method.

def be_scary(something)
  if(something.respond_to?(:roar!))
    something.roar!
  else
    raise "That thing cannot roar..."
  end
end

Great… but if the only thing you are going to do is raise an exception (something ruby would have done by itself), this kind of practice may be a little overkill. It’s up to you to decide if the extra effort is worth it or not.

Ducktyping is not polymorphism

The beauty of ducktyping is that it doesn’t rely on inheritance or polymorphism at all. Every single objects are accepted in every single methods, period. The only thing that matters is the capability of an object to do whatever the method is trying to do. If the object can’t, the interpreter will gladly raise an exception in time (unless you use some respond_to technique that is).

Give ducktyping a real chance

Ducktyping can shake the conceptions you have about types and classes in programming languages. At first, I was not sure if I liked the idea, but now I think that it is a very logical and clever way to manage types. I came to the realization that programming languages didn’t need that many boundaries after all. I even wonder why no one thought about ducktyping before. Where’s the catch?

An introduction to code blocks

What is a code block anyway? Well, a code block is a chunk of code… that’s all there is to say about it. I know, this part is not really interesting. What IS interesting though, is that you can pass a block to a ruby function and then have this function call the block whenever it wants. C++ programmers might think these code blocks are the equivalent of function pointers. Well, they maybe are, but there are some key differences. In ruby, you can pass a code block to ANY ruby method, not just the methods that expect a parameter of a certain type. Every ruby methods can receives a block, regardless of the number of parameters they accept. That may sound confusing, but in fact it is just that you don’t pass a code block to a function like if it was a standard parameter (well, you could… but that’s beyond the scope of this article).
Let’s see how it works :
Here is an example of a method who decides to call a block that may have been passed to it by the caller

def my_ordinary_method()
  #do stuff
  yield #the instruction that calls the block
  #do more stuff
end

See how there is no parameter representing the block to call? There’s no parameter of type TBlockCode or anything of the sort. my_ordinary_method is just a regular method with one small exception : That method decided to make use of the “yield” method in it’s implementation to call an eventual block that might have been passed to it by the caller.
Now, let’s see how the caller can pass a code block to my_ordinary_method

def the_caller()
  #do stuff
  my_ordinary_method() do
    puts "I am the block. The one everyone talks about!"
    puts "I am gentle, colorful and polite"
  end
end

A code block is just a chunk of code between the keyword do and the keyword end. (you can use { and } instead if you want).
You can also pass parameters from the callee (the method that calls the block) to the caller. To achieve this, you have to place those parameters between two pipes (|) and separate them by commas. When you’re on the caller side, you can think of these parameters as containers waiting to be filled in. The method that will execute the block (callee) will fill them by passing the values the “standard way” via the yield method.
Let’s start from the beginning with this in mind :

def my_ordinary_method()
  i=6 #6 is a number I like
  j=9 #I don't have any feelings towards this number
  yield(i,j) #call the block
end
def the_caller()
  #do stuff
  my_ordinary_method() do |fill_me, fill_me_too|
    puts fill_me  #will writes 6 on the screen
    puts fill_me_too #will writes 9 on the screen
  end
end

Code blocks are extremely useful and powerful. They are used a lot by ruby programmers to achieve what we could call “intelligent iterations”. For example, there is a method called times in the Integer class. Well, times is a method that makes use of the yield keyword in it’s implementation. You realize what does this means right? Yep, you can pass a code block to it!
Let’s see how the times method in the class Integer could be implemented (the code is invalid…but it doesn’t matter).

class Integer
  #the getter and setter that holds the internal numerical value
  #of the Integer instance.
  def internal_value
    #variables preceded by @ are instance variables
    return @internal_value
  end
  def internal_value=(internal_value)
    @internal_value = internal_value
  end
  #Now, the times method
  def times
    #regular loop. As you can see, the actual looping is done by
    #the callee, NOT by the caller
    for i=0 to @internal_value-1
      yield
    end
  end
end

Now, let’s use that times method

6.times {puts "I... can't... believe... this..."}

I know, This kind of stuff impresses me a lot too. No need to play with the index, you just tell ruby that you want to display something on the screen 6 times. Now, that’s the kind of abstraction I love!