From: Jason Creighton Date: 2003-09-14T00:40:54+09:00 Subject: Re: Duck Typing On Sat, 13 Sep 2003 09:23:16 +0900 Jim Weirich wrote: > In the Method Redefinition thread, this explanation of Duck Typing is > offered ... > > > What Duck typing is based mostly on realising what sort of operations > > you want to do with the object and testing for those operations, > > rather than testing for the class. As Dave is fond of saying: type and > > class aren't the same. > > This is slightly different than my understanding of Duck Typing. I > would phrase it more like this: > > Duck typing is based mostly on realising what sort of operations > you want to do with the object and just doing them, rather than > worrying if the object inherits from the proper base class or > interface. > > I've heard others also explain duck typing in terms of explicitly > testing for particular methods and I feel that leaves the wrong > impression. If we say Ruby supports duck typing, then newcomers are > left with the impression that you need to do a lot of testing for > particular methods (which you don't). I agree completely. > I would call this an example of Duck Typing ... > > class Dog > def talk > puts "Woof" > end > end > class Duck > def talk > puts "Quack" > end > end > [Dog.new, Duck.new].each { |a| a.talk } > > .. even though there is no explicit method testing going on. After > all, if it walks and talks like a duck ... > > So, am I off base? No. That is how I think of Duck Typing as well. Just call the methods. Don't bother with method existence checking, Ruby does it for you. (By raising NoMethodError) Jason Creighton