Forum: Ruby on Rails The Ruby Way For Grouping And Sorting An Array

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
53d4002427665db72120f3fa0714ea52?d=identicon&s=25 Ruby.Me.Silly (Guest)
on 2007-04-01 15:50
(Received via mailing list)
I have an array of Rails ActiveRecord models in which I need to group
by name and then sort by topic.  For instance the initial array may
look like this (hopefully formatting comes out correctly):

Name          Topic
News           Politics
Sports         Soccer
Finance       Stocks
Finance       Bonds
News           World
News           Entertainment

I will need to display the list as follows:

Name           Topic
Finance        Bonds
News           Entertainment
Sports          Soccer

As you can see, we only display the name on the first entry of that
name.  Sure, I can simply sort a one-dimensional array of these
objects and place the logic into the presentation such that it checks
if the name it is processing now differs from the last name.  But that
didn't see so clean.  Is there a better Ruby way in doing this?
Fb23bc8cd4030c526b0689276b34c8bd?d=identicon&s=25 Bryan Duxbury (bryanduxbury)
on 2007-04-01 19:56
Is your Topic not a proper ActiveRecord model? It seems like you have a
one-to-many relationship. If you have Topic and, say, SubTopics, you
should just traverse the Topics first, then their SubTopics. You can
even get all the data in one query with :include.
This topic is locked and can not be replied to.