From: Daniel N Date: 2006-12-07T13:55:39+09:00 Subject: Re: [GOLF]: partitioning an array ------=_Part_43344_17292931.1165467335014 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit Content-Disposition: inline On 12/7/06, Max Muermann wrote: > > Take an array of objects and partition it into subarrays, based on > some arbitrary property of the objects. I would use this for example > for generating a report of purchase orders and grouped by week, month, > year, approximate value, etc. > > The idea is similar to Array#partition, but where partition only does > a true/false check, the resulting array should be partitioned by the > return value of a block so that: > > a = ['a','bc','def','g','hi','jkl','m'] > group(a) {|i| i.size} #=> [["a", "g", "m"], ["bc", "hi"], ["def", "jkl"]] > > > My best effort so far is this: > > def group array, &block > h = {} > array.each do |e| > (h[yield(e)]||=[])< end > h.to_a.map {|e| e[1] } > end def group a a.inject({}){|h,v|(h[yield(v)]||=[])<