login

DuckTyping (Ruby)

HomePage | RecentChanges | Preferences | Wikis | RubyGarden | Feed-icon-16x16

This page contains changes that are awaiting review.
The interesting notion of "duck typing" has been widely misunderstood and misused. To get a fix on it, see the description and explication by Dave Thomas, the person who coined the term, at http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/78502. Reproduced below:

Duck typing is way of thinking about programming in Ruby.

For folks who come from languages such as Java or C++, types are 
basically the same as classes. When you ask 'what is the type of 
"cat"?', the answer comes back as 'String'.

These languages use the type==class model as the model for programming. 
You say

     String fred;

to say that 'fred' has type 'String', and the language implements that 
by saying that fred can only reference objects that are class String.

Ruby doesn't use that model. In Ruby, types are defined as the 
capabilities of objects. Classes can be used to give objects their 
initial capabilities, but from that point on, the class is (almost) 
irrelevant. When I write

     fred << "dog"

in Ruby, I don't care whether fred is a String, a File, or an Array (a 
fact that's very useful when writing unit tests).

I call this duck typing for two reasons. First, because the name fits 
(the "walk like a duck" business). Second, because I want to give a name 
to it to remind folks that Ruby's type model _is_ different.

Cheers,
Dave


HomePage | RecentChanges | Preferences | Wikis | RubyGarden
Edit text of this page | View other revisions
Rev 8, Last edited at March 30, 2008 22:26 pm by anonymous / none (diff)
Find: