Descending sort by value of a Hash in Ruby

RubySortingHash

Ruby Problem Overview


My input hash: h = { "a" => 20, "b" => 30, "c" => 10 }

Ascending sort: h.sort {|a,b| a[1]<=>b[1]} #=> [["c", 10], ["a", 20], ["b", 30]]

But, I need [["b", 30], ["a", 20], ["c", 10]]

How is can we make it work the other way around, what does <=> mean?

Ruby Solutions


Solution 1 - Ruby

You can have it cleaner, clearer and faster, all at once! Like this:

h.sort_by {|k,v| v}.reverse

I benchmarked timings on 3000 iterations of sorting a 1000-element hash with random values, and got these times:

h.sort {|x,y| -(x[1]<=>y[1])} -- 16.7s
h.sort {|x,y| y[1] <=> x[1]} -- 12.3s
h.sort_by {|k,v| -v} -- 5.9s
h.sort_by {|k,v| v}.reverse -- 3.7

Solution 2 - Ruby

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

Solution 3 - Ruby

<=> compares the two operands, returning -1 if the first is lower, 0 if they're equal and 1 if the first is higher. This means that you can just do -(a[1]<=>b[1]) to reverse the order.

Solution 4 - Ruby

Super simple: h.sort_by { |k, v| -v }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionzengrView Question on Stackoverflow
Solution 1 - Rubyglenn mcdonaldView Answer on Stackoverflow
Solution 2 - RubycethView Answer on Stackoverflow
Solution 3 - RubyChuckView Answer on Stackoverflow
Solution 4 - RubyPaul OdeonView Answer on Stackoverflow