# The Ruby Way For Grouping And Sorting An Array

**URL:** <https://www.ruby-forum.com/t/the-ruby-way-for-grouping-and-sorting-an-array/90780>\
**Category:** Rails\
**Created:** [April 1, 2007, 3:50pm UTC](https://www.ruby-forum.com/t/the-ruby-way-for-grouping-and-sorting-an-array/90780 "2007-04-01T15:50:23Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Ruby.Me.Silly](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/22d042/32.png) [@Ruby.Me.Silly](https://www.ruby-forum.com/u/Ruby.Me.Silly)\
**Post date:** [April 1, 2007, 3:50pm UTC](https://www.ruby-forum.com/t/the-ruby-way-for-grouping-and-sorting-an-array/90780/1 "2007-04-01T15:50:23Z")

</div>

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  
Stocks  
News Entertainment  
Politics  
World  
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?

---

<div class="post-metadata">

**Author:** ![Ruby.Me.Silly](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/22d042/32.png) [@Ruby.Me.Silly](https://www.ruby-forum.com/u/Ruby.Me.Silly)\
**Post date:** [April 1, 2007, 7:56pm UTC](https://www.ruby-forum.com/t/the-ruby-way-for-grouping-and-sorting-an-array/90780/2 "2007-04-01T19:56:35Z")

</div>

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.
