Forum: Ruby on Rails What's the purpose of index_by over group_by?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Michael C. (Guest)
on 2007-05-13 21:43
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.
Rick O. (Guest)
on 2007-05-14 01:42
(Received via mailing list)
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] #=> [<Event>, <Event>, ...]

--
Rick O.
http://lighthouseapp.com
http://weblog.techno-weenie.net
http://mephistoblog.com
Michael C. (Guest)
on 2007-05-14 16:12
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.
This topic is locked and can not be replied to.