diff --git a/lib/utils.rb b/lib/utils.rb index 4a8ad396..db3f015e 100644 --- a/lib/utils.rb +++ b/lib/utils.rb @@ -94,9 +94,8 @@ module Utils def <=> other other = other.array @array.each_with_index do |e, i| - case cmp = e <=> other[i] - when nil - return nil + o = other[i] + case cmp = e <=> o || e.to_s <=> o.to_s when 0 next else diff --git a/spec/lib/utils_spec.rb b/spec/lib/utils_spec.rb index 26125771..84651923 100644 --- a/spec/lib/utils_spec.rb +++ b/spec/lib/utils_spec.rb @@ -153,5 +153,23 @@ describe Utils do Utils.sort_tuples!(tuples, orders) expect(tuples).to eq expected end + + it "always succeeds in sorting even if it finds pairs of incomparable objects" do + time = Time.now + tuples = [ + [2, "a", time - 1], # 0 + [1, "b", nil], # 1 + [1, "b", time], # 2 + ["2", nil, time], # 3 + [1, nil, time], # 4 + [nil, "a", time + 1], # 5 + [2, "a", time], # 6 + ] + orders = [true, false, true] + expected = tuples.values_at(3, 6, 0, 4, 2, 1, 5) + + Utils.sort_tuples!(tuples, orders) + expect(tuples).to eq expected + end end end