Make TupleSorter#sort! never fail

If comparison of two objects fails, they are compared as strings.

Akinori MUSHA 9 年之前
父节点
当前提交
8c2b11a567
共有 2 个文件被更改,包括 20 次插入3 次删除
  1. 2 3
      lib/utils.rb
  2. 18 0
      spec/lib/utils_spec.rb

+ 2 - 3
lib/utils.rb

@@ -94,9 +94,8 @@ module Utils
94 94
       def <=> other
95 95
         other = other.array
96 96
         @array.each_with_index do |e, i|
97
-          case cmp = e <=> other[i]
98
-          when nil
99
-            return nil
97
+          o = other[i]
98
+          case cmp = e <=> o || e.to_s <=> o.to_s
100 99
           when 0
101 100
             next
102 101
           else

+ 18 - 0
spec/lib/utils_spec.rb

@@ -153,5 +153,23 @@ describe Utils do
153 153
       Utils.sort_tuples!(tuples, orders)
154 154
       expect(tuples).to eq expected
155 155
     end
156
+
157
+    it "always succeeds in sorting even if it finds pairs of incomparable objects" do
158
+      time = Time.now
159
+      tuples = [
160
+        [2,   "a", time - 1],  # 0
161
+        [1,   "b", nil],       # 1
162
+        [1,   "b", time],      # 2
163
+        ["2", nil, time],      # 3
164
+        [1,   nil, time],      # 4
165
+        [nil, "a", time + 1],  # 5
166
+        [2,   "a", time],      # 6
167
+      ]
168
+      orders = [true, false, true]
169
+      expected = tuples.values_at(3, 6, 0, 4, 2, 1, 5)
170
+
171
+      Utils.sort_tuples!(tuples, orders)
172
+      expect(tuples).to eq expected
173
+    end
156 174
   end
157 175
 end