Sorting Question

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

Hi –

On 4/26/07, Mick [email protected] 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

great that should help a lot cheers!

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs