Morton Goldberg
10/20/2007 11:17:00 PM
On Oct 19, 2007, at 9:05 PM, William James wrote:
> On Oct 19, 2:01 pm, Sam Kong <sam.s.k...@gmail.com> wrote:
>> I thought this would be a common need but I couldn't find a method.
>>
>> Let's say I have an array of objects. I want to group the elements
>> by a property of objects.
>>
>> people.group_by do |person|
>> person.age
>> end
>>
>> The above method should return an array of arrays grouped by age.
>>
>> What's the ruby way for this case? I think I can implement it but
>> I am sure that a good way already exists.
>
> It's pretty simple.
>
> class Array
> def group_by
> h = Hash.new{ [] }
> each{|x|
> h[ yield( x ) ] += [ x ]
> }
> h.values
> end
> end
That's good, but I think the following modification makes it a
little better:
<code>
class Array
def group_by
h = Hash.new { |h, k| h[k] = [] }
each { |item| h[yield(item)] << item }
h.values
end
end
</code>
Regards, Morton