From: Adam Shelly Date: 2008-09-09T03:15:58+09:00 Subject: Re: Is this a sensible implementation for Array#group_by ? On Mon, Sep 8, 2008 at 10:04 AM, Max Williams wrote: > I was looking for a method to split an array into smaller arrays based > on some property of the members (set with a code block). I came up with > the following and wanted to know what you guys think about a) whether > it's sensible b) whether it's been done already: > > class Array > def group_by > result_array = [] > self.each do |element| > key = yield element > if (found = result_array.assoc(key)) > found[1] << element > else > result_array << [key, [element]] > end > end > return result_array.collect{|a| a[1]} > end > end > > I'm just after some feedback really. I'm guessing i just couldn't find > the good implementation of it :) It seems sensible to me, although I'd use a hash instead of a associative array - it just looks cleaner. I didn't check the performance difference though. class Array def group_by result={} self.each do |element| (result[yield(element)]||=[]) << element - end return result.values end end I think the Facets library already has a similar method. -Adam