Sorting an array in descending order in Ruby.

Posted by Waseem on Stack Overflow See other posts from Stack Overflow or by Waseem
Published on 2010-04-15T01:32:30Z Indexed on 2010/04/15 1:33 UTC
Read the original article Hit count: 286

Filed under:
|

Hi,

I have an array of hashes like following

[
  { :foo => 'foo', :bar => 2 },
  { :foo => 'foo', :bar => 3 },
  { :foo => 'foo', :bar => 5 },
]

I am trying to sort above array in descending order according to the value of :bar in each hash.

I am using sort_by like following to sort above array.

a.sort_by { |h| h[:bar] }

However above sorts the array in ascending order. How do I make it sort in descending order?

One solution was to do following:

a.sort_by { |h| -h[:bar] }

But that negative sign does not seem appropriate. Any views?

© Stack Overflow or respective owner

Related posts about ruby

Related posts about sorting