Thursday, October 18, 2007

ruby group_by

I often need to convert an array of objects into a hash, indexed by some attribute of the objects.

For e.g. for a task list, each task is an object consisting of
- type (e.g grocery, auto)
- name (e.g. Safeway, Lucky, OSH)
- notes

So a task list may look like
[
[ :type => :grocery, :name => :safeway, :notes => "buy some milk" ],
[ :type => :grocery, :name => :lucky :notes => "buy halloween candy" ],
[ :type => :auto, :name => :costco :notes => "buy tires for the acura" ]
]

For display purposes I would like to organize the tasks by their type and then by names.

Updated: Rails makes it so easy :)
@tasks = {}
TaskList.find(:all).group_by(&:type) do |type, subtasks|
@tasks[type] = subtasks.group_by(&:name)
end

2 comments:

Ryan Long said...

That's awesome, right! It is however a feature of Rails, not Ruby. Grouping a hash in Ruby is not quite so simple...

Anonymous said...

group_by is now in bare bones Ruby, as of Ruby 1.8.7 / Ruby 1.9.