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