Thursday, November 20, 2008

Method of the Day: index_by

Just stumbled on to this one. I can't tell you how many times I've wanted this functionality. You have an array, but you want a hash keyed by an attribute of the items in the array. Typically, you'd do something like this:
users_by_name = {}
users.each { |u| users_by_name[u.name] = u }
Which is of course silliness now that we know about index_by.
users_by_name = users.index_by(&:name)
Slick.

No comments: