From: ara.t.howard@... Date: 2006-12-07T13:25:21+09:00 Subject: Re: [GOLF]: partitioning an array On Thu, 7 Dec 2006, 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 > > For some reason, I cannot bring myself to like this. I have the > nagging feeling that there is a more elegant way... > > Cheers, > Max it's not a good golf solution, but here's a slightly differnet approach: harp:~ > cat a.rb module Enumerable def group_by &b h = Hash.new{|h,k| h[k] = []} each{|x| h[x.instance_eval(&b)] << x} h.values end end a = %w[ a bc def g hi jkl m ] p a.group_by{ size } h = { 'k' => 'v', 'K' => 'V', 'a' => 'b', 'A' => 'b' } p h.group_by{ first.downcase } harp:~ > ruby a.rb [["a", "g", "m"], ["bc", "hi"], ["def", "jkl"]] [[["K", "V"], ["k", "v"]], [["A", "b"], ["a", "b"]]] regards. -a -- if you want others to be happy, practice compassion. if you want to be happy, practice compassion. -- the dalai lama