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] }
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] }
Well I made the same mistake in blog entry ;-)
Is there a reason why you can’t just do:
h.sort {|a,b| b[1] a[1]}
@Aaron
I guess there is no reason :) At this time I was still learning Ruby (it was 2007 :)) )
h.sort_by(&:last) is a nice compact way of sorting by values