From: Morton Goldberg Date: 2007-10-21T08:17:12+09:00 Subject: Re: What's the ruby way of grouping elements of an array? On Oct 19, 2007, at 9:05 PM, William James wrote: > On Oct 19, 2:01 pm, Sam Kong 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: class Array def group_by h = Hash.new { |h, k| h[k] = [] } each { |item| h[yield(item)] << item } h.values end end Regards, Morton