Florian Growrote:
> Moin.
> 
> Here's two small RFEs. I think both of these are generally useful, but 
> it feels wrong to go through the rather complex RCR process for such 
> simple feature requests. If you disagree with that please let me know.
> 
> 
> enum.group_by { |item| ... } (Enumerable#group_by):
> 
> Groups the elements of an Enumerable into a matching group. The block is 
> used for mapping an item to a group.
> 
> %w(hello world ruby rocks a very lot).group_by { |word| word.size }
> # => {1 => ["a"], 3 => ["lot"], 4 => ["ruby", "very"], 5 => ["rocks"]}
> %w(foo bar bark qux quv).group_by { |word| word[0, 1] }
> # => {"b" => ["bar", "bark"], "f" => ["foo"], "q" => ["qux", "quv"]}
> 
> files.group_by { |file| File.size(file) }
> users.group_by { |user| user.age }
> 
> Ruby implementation:
> 
> module Enumerable
>   def group_by
>     result = Hash.new { |h, k| h[k] = Array.new }
>     self.each do |item|
>       group = yield(item)
>       result[group] << item
>     end
>     return result
>   end
> end

It's even better if you allow customization on the storage (in your case 
hard-coded to be a Hash):

module Enumerable
   def group_by(store=Hash.new)
     self.each do |elem|
       group = yield elem
       (store[group] ||= []) << elem
     end
     store
   end
end


You can find the additional test case here:

http://www.ntecs.de/viewcvs/viewcvs/Misc/

TC_group_by.rb

Regards,

   Michael