What's the purpose of index_by over group_by?


#1

If I understand how the two work, the only difference between them would
be that group_by assembles the objects into an array, so to access all
the items that match by name,

items[“name”][0]
items[“name”][1]…

whereas index_by stores the object directly instead of an array of
objects, thus it can only return one item per key,

items[“name”] would return the only object that has the given attribute
“name”, so index_by should only be used if you don’t expect two items to
have a given attribute of the same value.

My question is, if in your situation index_by is enough, wouldn’t
group_by and items[“name”][0] yield the same result as index_by
items[“name”]? Isn’t it safer to use group_by anyways incase there are
two or more items that would fall under the same key?

I may be overlooking something, which is why I’m asking, is there any
real purpose for index_by over group_by or have I entirely misunderstood
how the two work? Keeping in mind I have not had the opportunity to use
either yet, just reading about how the two methods work.


#2

On 5/13/07, Michael C. removed_email_address@domain.invalid wrote:

real purpose for index_by over group_by or have I entirely misunderstood
how the two work? Keeping in mind I have not had the opportunity to use
either yet, just reading about how the two methods work.

Nope, you’ve got it. Use index_by when each hash key only has one
value, use group_by when there are mutliples. Here are two examples:

@users = User.find(:all).index_by { |u| u.id }
@users[5] # => <User…>

@events = Event.find(:all).group_by { |e| e.created_at.to_date }
@events[Date.today] #=> [, , …]


Rick O.
http://lighthouseapp.com
http://weblog.techno-weenie.net
http://mephistoblog.com


#3

The drastically different approach Agile Web D. uses to explain
one over the other without comparing the marginal difference made me
think I was missing something. So that’s all there is to it then.
Thanks.