NetManiac

Witold Rugowski on web20 wave with Ruby on Rails

Sorting hash by values

Posted on June 11, 2007 - Filed Under Ruby

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]) }

Popularity: 22% [?]

Hits for this post: 10762

Similar Posts

Comments

2 Responses to “Sorting hash by values”

  1. mcv on June 11th, 2007 14:18

    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] }

  2. NetManiac on June 11th, 2007 14:28

    Well I made the same mistake in blog entry ;-)

Leave a Reply