inquisitive
inquisitive

Reputation: 3974

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

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]]

Upvotes: 5

Views: 2329

Answers (1)

user12341234
user12341234

Reputation: 7193

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]]

Upvotes: 9

Related Questions