From: Eric Mahurin Date: 2006-08-26T22:25:23+09:00 Subject: Re: Duck typing alows true polymorfisim ------=_Part_78786_28301241.1156598722538 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit Content-Disposition: inline On 8/25/06, atbusbook@aol.com wrote: > > lets say you want a generic numerical algorithom like sum > > Ruby > > def sum lst > lst.inject(0){|total,current| total*current} > end > > Java // i dont know if there is a numeric super class for numbers > > class Sum{ > public static int sum(int[] lst){ > int total = 0; > for(int current : lst){ > total+=current; > } > return total; > } > // repeat for all other number types > } > The title of this thread was almost like a post I made a year or so ago: http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/145049 What you wrote still isn't as generic as it could be. This can handle more than just numerics: def sum enum enum.inject{ |total,current| total+current } end enum can be anything that responds to inject (likely an Enumerable) with a block that takes 2 arguments where the first responds to +. If enum is an Enumerable, this means the first element responds to + which returns something that also continues to respond to +. Now you can do this: three = sum([1,2]) hello_world = sum(["hello","world"]) concatenated_lines = sum(anIO) The simpler you can make the description of the duck-typing of a method, the more generic and flexible it will be. By adding a 0 argument to inject, you made the duck-typing a little more complex and stiffled it by only allowing elments that can be added to 0. ------=_Part_78786_28301241.1156598722538--