Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Descending sort by value of a Hash in Ruby

Tags:

sorting

ruby

hash

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?

like image 289
zengr Avatar asked Nov 24 '10 06:11

zengr


People also ask

What is <=> in Ruby sort?

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.

What hash function does Ruby use?

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.


2 Answers

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 
like image 144
glenn mcdonald Avatar answered Oct 23 '22 03:10

glenn mcdonald


h.sort {|a,b| b[1]<=>a[1]} 
like image 21
ceth Avatar answered Oct 23 '22 04:10

ceth