From: Daniel Schierbeck Date: 2006-11-30T03:16:30+09:00 Subject: Re: Array#group_by On Wed, 2006-11-29 at 22:55 +0900, Gareth Adams wrote: > class Array > # Groups elements of an array based on a user-defined condition > # > # Each element from this array is passed to the block, and the returned value > # determines the key under which it will be stored in the output hash > # > # If no block is given then the array indices will be used as the hash keys > def group_by > hsh = {} > self.dup.each_with_index do |element, i| > if block_given? > key = yield element > else > key = i > end > hsh[key] ||= [] > hsh[key] << element > end > hsh > end > end Here's an improved version: module Enumerable def group_by hsh = Hash.new{|hsh, key| hsh[key] = [] } if block_given? each{|obj| hsh[yield(obj)].push(obj) } else each_with_index{|obj, i| hsh[i].push(obj) } end hsh end end Cheers, Daniel Schierbeck