From: Max Williams Date: 2008-09-09T02:04:21+09:00 Subject: Is this a sensible implementation for Array#group_by ? 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 >> arr = %w(apple banana pear plum nectarine orange melon) => ["apple", "banana", "pear", "plum", "nectarine", "orange", "melon"] #group by length of name >> arr.group_by{|s| s.length} => [["apple", "melon"], ["banana", "orange"], ["pear", "plum"], ["nectarine"]] #group by whether it has an e >> arr.group_by{|s| (s =~ /e/) == nil} => [["apple", "pear", "nectarine", "orange", "melon"], ["banana", "plum"]] One thing i haven't done is make it sort: since the grouping key is just an object and most objects aren't sortable. I could get round this but not without slowing it down and the user can always sort the results by comparing the first member of each subarray. I'm just after some feedback really. I'm guessing i just couldn't find the good implementation of it :) -- Posted via http://www.ruby-forum.com/.