I have an array of hashes:

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

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

I am using sort_by to sort above array:

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

However, this 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.

8 Answers
8

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *