Sorting hash by values

Sorting hash by values is quite straightforward. You don’t have to search long to find this example in Ruby documentation:

 h.sort {|a,b| a[1] <=> b[1]} 

sort method takes hash converts it in array of two elements arrays and then sort it as an array. When called without code block, sorts hash by keys. But when You provide code block, it can take two args which are two hash elements written as array [ key, value ], so comparing values and sorting by them is trivial task as in example above.

But what to do if You want to reverse sort order? Negation does not work with operator <=>. This operator returns 1, 0 or -1 depending on relation between objects. To reverse results You just have to multiply result by -1. So now You can sort with:

 h.sort {|a,b| -1*(a[1]<=>b[1]) } 

UPDATE
As suggested in comments simpler is just reverse arguments order and sort it with:

 h.sort {|a,b| -b[1]<=>a[1] } 

Join the Conversation

5 Comments

  1. You miss information that this comment form interprets <s and >s. ;-)

    Again: instead of
    h.sort { |a, b| -1*(a[1] <=> b[1]) }
    reverse order of a and b:
    h.sort { |a, b| b[1] <=> a[1] }

Leave a comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.