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?
The Ruby sort method works by comparing elements of a collection using their <=> operator (more about that in a second), using the quicksort algorithm. You can also pass it an optional block if you want to do some custom sorting. The block receives two parameters for you to specify how they should be compared.
In Ruby, Hash is a collection of unique keys and their values. Hash is like an Array, except the indexing is done with the help of arbitrary keys of any object type. In Hash, the order of returning keys and their value by various iterators is arbitrary and will generally not be in the insertion order.
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
h.sort {|a,b| b[1]<=>a[1]}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With