Sort the hash by value in descending order, and then type in ascending 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 value:
my_hash = trial_hash.sort_by{|k, v| v}.reverse I get it like this:
[["key1", 1000], ["key4", 500], ["key5", 500], ["key6", 500], ["key3", 500], ["key2", 34]] But I want it to be sorted in ascending order when the value is the same. How can I do it?
For example: the above hash will be ordered this way:
[["key1", 1000], ["key3", 500], ["key4", 500], ["key5", 500], ["key6", 500], ["key2", 34]] When comparing, arrays are first evaluated by the first elements, then by their second, etc. You can use this fact to list successive comparisons. Comparison 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]]