Ruby:对包含nil的多维数组进行排序有时会失败

jon*_*oni 11 ruby arrays sorting

我在其中一个项目的测试失败中找到了这个例子.为什么这样做:

[[1,2,3], [2,3,4], [1,1,nil]].sort
#=> [[1, 1, nil], [1, 2, 3], [2, 3, 4]]
Run Code Online (Sandbox Code Playgroud)

但这不是:

[[1,2,3], [nil,3,4], [1,1,nil]].sort
#=> ERROR: ArgumentError: comparison of Array with Array failed
Run Code Online (Sandbox Code Playgroud)

经过测试的Ruby版本:2.0.0, 1.9.3.

Ada*_*amT 12

它失败了,因为它已经过去了nil.第一个测试示例没有失败的原因是因为比较1, 1发生了1, 2.它没有尽可能nil地验证,因为它不需要.

下面的示例失败,因为它必须在nil最初进行.在irb中尝试一下:

[1, nil, 2].sort
ArgumentError: comparison of Fixnum with nil failed

# in this example 1,2 comes before 2,1 so no need to continue in sort
# and nil is never reached
[ [2,1,3,5], [1,2,nil,6] ].sort
 => [[1, 2, nil, 6], [2, 1, 3, 5]]
Run Code Online (Sandbox Code Playgroud)

  • 更短:`[1,2,nil] .sort_by&:to_i` (3认同)
  • 好吧,这是解决此问题的方法:`[1,2,nil] .sort {| x,y | x.to_i <=> y.to_i}`,因为有人可能会在寻找它。 (2认同)