boddhisattva
boddhisattva

Reputation: 7380

Sort hash having duplicate values in ascending order of keys

I have a hash that looks like this:

{"P1"=>108, "P6"=>50, "P3"=>50, "P5"=>40, "P2"=>40, "P4"=>40}

This is already sorted in the descending order of value.

I want the output below, where the original ordering (by value descending) is maintained, but the elements with the same values are sorted in ascending order of keys (for e.g., P3 comes before P6).

{"P1"=>108, "P3"=>50, "P6"=>50, "P2"=>40, "P4"=>40, "P5"=>40 }

Any pointers of approaching this in a simple way would be helpful.

Upvotes: 0

Views: 520

Answers (1)

sawa
sawa

Reputation: 168101

For multiple conditions for sort, use an array.

{"P1"=>108, "P6"=>50, "P3"=>50, "P5"=>40, "P2"=>40, "P4"=>40}
.sort_by{|k, v| [-v, k]}.to_h

Upvotes: 1

Related Questions