Sorting Question

Hi --

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