I'm trying to reverse sort an array of hashes without changing the order of hashes that are equal. However I am not seeing this functionality with sort.
For example,
[{a:1, b:2}, {a:0, b:5}, {a:1,b:4}, {a:1,b:3}].sort { |a,b| b[:a] <=> a[:a] }
# actual: [{:a=>1, :b=>2}, {:a=>1, :b=>3}, {:a=>1, :b=>4}, {:a=>0, :b=>5}]
# expected: [{:a=>1, :b=>2}, {:a=>1, :b=>4}, {:a=>1, :b=>3}, {:a=>0, :b=>5}]
The hashes with :b=>4 and :b=>3 are incorrectly re-ordered. Am I misinterpreting how sort works?
Array#sort uses a quicksort algorithm under the hood. This algorithm is not stable: there is no guarantee that equal elements will not be reordered in the output. Basically when you sort in Ruby, you should specify exactly how things should be sorted rather than leave it up to chance. You can handle your case by using sort_by and adding the element's index to the sorting criteria:
ary.sort_by.with_index { |h, i| [-h[:a], i] }
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