On Oct 19, 2007, at 3:01 PM, Sam Kong wrote:

> Hi,
>
> 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.
>
> Thanks.
>
> Sam
> -- 
> Posted via http://www.ruby-forum.com/.

ActiveSupport (part of Rails, but usable separately as a gem) does this:

http://api.rubyonrails.org/classes/Enumerable.html#M001111
     # File vendor/rails/activesupport/lib/active_support/core_ext/ 
enumerable.rb, line 17
17:   def group_by
18:     inject({}) do |groups, element|
19:       (groups[yield(element)] ||= []) << element
20:       groups
21:     end
22:   end

This returns a hash of age=>[people], but you could deal with that  
by .values or sorting or whatever makes the most sense for your  
application.

-Rob

Rob Biedenharn		http://agileconsultingllc.com
Rob / AgileConsultingLLC.com