# Sorting Question

**URL:** <https://www.ruby-forum.com/t/sorting-question/92995>\
**Category:** Rails\
**Created:** [April 26, 2007, 12:36pm UTC](https://www.ruby-forum.com/t/sorting-question/92995 "2007-04-26T12:36:26Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![mick](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/f04885/32.png) [@mick](https://www.ruby-forum.com/u/mick)\
**Post date:** [April 26, 2007, 12:36pm UTC](https://www.ruby-forum.com/t/sorting-question/92995/1 "2007-04-26T12:36:26Z")

</div>

Hello

I would like to have a structure, with each item in the structure  
consisting of an id, and a count value.

I would then like to sort the structure based on the count value  
descending. Does anyone know of any way of doing this or has done a  
similar type of thing before and is willing to offer some help?

Cheers guys,

Mick

---

<div class="post-metadata">

**Author:** ![mick](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/f04885/32.png) [@mick](https://www.ruby-forum.com/u/mick)\
**Post date:** [April 26, 2007, 1:14pm UTC](https://www.ruby-forum.com/t/sorting-question/92995/2 "2007-04-26T13:14:48Z")

</div>

Hi –

On 4/26/07, Mick [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> Hello
> 
> I would like to have a structure, with each item in the structure  
> consisting of an id, and a count value.
> 
> I would then like to sort the structure based on the count value  
> descending. Does anyone know of any way of doing this or has done a  
> similar type of thing before and is willing to offer some help?

It depends on what kind of structure it is exactly, but for example if  
you’ve got an array of arrays, you can do something like this:

> > a = [[1,3], [5,2], [2,4], [6,7] ]  
> > =\> [[1, 3], [5, 2], [2, 4], [6, 7]]  
> > a.sort\_by {|id,c| -c }  
> > =\> [[6, 7], [2, 4], [1, 3], [5, 2]]

If it’s an ActiveRecord association or find operation you could use  
:order =\> “count DESC” (assuming a count column in the table). If it’s  
an array of Ruby objects with a count method, you could do:

structure.sort\_by {|item| -item.count }

David

–  
Upcoming Rails training by Ruby Power and Light:  
Four-day Intro to Intermediate  
May 8-11, 2007  
Edison, NJ  
[http://www.rubypal.com/events/05082007](http://www.rubypal.com/events/05082007)

---

<div class="post-metadata">

**Author:** ![mick](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/f04885/32.png) [@mick](https://www.ruby-forum.com/u/mick)\
**Post date:** [April 26, 2007, 1:18pm UTC](https://www.ruby-forum.com/t/sorting-question/92995/3 "2007-04-26T13:18:51Z")

</div>

great that should help a lot cheers!
