Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort a hash by value in descending order and then key in ascending order ruby

Tags:

sorting

ruby

hash

I have a hash like this

 trial_hash ={"key1"=>1000, "key2"=>34, "key3"=>500, "key4"=>500, "key5"=>500, "key6"=>500}

I order it in descending order of the value:

 my_hash = trial_hash.sort_by{|k, v| v}.reverse

I get it this way now:

 [["key1", 1000], ["key4", 500], ["key5", 500], ["key6", 500], ["key3", 500], ["key2", 34]]

But I want it to be sorted in ascending order of key when the value is same. How do I do it?

For eg: The above hash would be ordered this way:

 [["key1", 1000], ["key3", 500], ["key4", 500], ["key5", 500], ["key6", 500], ["key2", 34]]
like image 827
inquisitive Avatar asked May 21 '15 21:05

inquisitive


1 Answers

In a comparison, arrays get evaluated first by their first elements, then by their second, etc. You can use this fact to enumerate sequential comparisons. Comparing by [-v, k] first sorts by value (in reverse order) then by key.

>> trial_hash.sort_by{|k, v| [-v, k]}
=> [["key1", 1000], ["key3", 500], ["key4", 500], ["key5", 500], ["key6", 500], ["key2", 34]]
like image 176
user12341234 Avatar answered Sep 25 '22 22:09

user12341234