7
@cases => [{"name"=>"25 Cases per 60 day", "count"=>0},
 {"name"=>"30 Cases for 60 days", "count"=>8},
 {"name"=>"10 Cases per 60 days", "count"=>5}]

If I have an object which contains the previous results how can I sort by count in DESC order? To get the instance variable cases I did

ClassName.all.collect{|e| {'name' => e.name, 'count' => e.contracts.count}}
thedevlpr
  • 1,101
  • 12
  • 28
  • Refer to http://stackoverflow.com/questions/3154111/how-do-i-sort-an-array-of-hashes-by-a-value-in-the-hash – rlecaro2 Jan 30 '14 at 17:57

1 Answers1

17
sorted = @cases.sort_by{ |hash| hash['count'] }.reverse
sorted = @cases.sort_by{ |hash| -hash['count'] }
sorted = @cases.sort_by{ |hash| -(hash['count'] || 0) }

The first is the simplest.

The second is what I would do.

The third is what you can do if some of the hashes are missing a 'count' value.

Phrogz
  • 296,393
  • 112
  • 651
  • 745