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

Descending sort by hash value in Ruby

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

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

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

How can we make it work the other way around, which means <=> ?

+56
sorting ruby hash
Nov 24 2018-10-10T00
source share
4 answers

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

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

I conducted comparative timings for 3000 iterations of sorting a hash with 1000 elements with random values ​​and got the following points:

 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 
+149
Nov 24 '10 at 11:59
source share
β€” -
 h.sort {|a,b| b[1]<=>a[1]} 
+10
Nov 24 '10 at 6:52
source share

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

+8
Nov 24 '10 at 6:51
source share

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

+4
Sep 21 '15 at 13:47
source share



All Articles