Mills Thomas (app1tam) wrote:


> I guess I'm not sure what duck typing is, then.  My example was assuming I
> was using the original method from my first post.  Thus, duckness is a list
> of ducky methods.  My second example was selling myRobot to a duckHerder
> since, for all intents and purposes, myRobot acts like a duck.  The
> duckHerder would also consider myRobot to be a duck, assuming we agreed on
> duckness.  I thought that was duck-typing.

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