我想先按字符串对数组进行排序,然后再按数字对数组进行排序。我该怎么做?
最佳答案
解决棘手排序的一般技巧是使用#sort_by,该 block 返回具有主要和次要排序顺序的数组(如果需要,还可以返回第三等)
a = ['foo', 'bar', '1', '2', '10']
b = a.sort_by do |s|
if s =~ /^\d+$/
[2, $&.to_i]
else
[1, s]
end
end
p b # => ["bar", "foo", "1", "2", "10"]
之所以可行,是因为 Ruby 定义了数组比较的方式。比较由 Array#<=> 定义方法:
Arrays are compared in an “element-wise” manner; the first element of ary is compared with the first one of other_ary using the <=> operator, then each of the second elements, etc… As soon as the result of any such comparison is non zero (i.e. the two corresponding elements are not equal), that result is returned for the whole array comparison.
关于ruby - 在 Ruby 中对字符串和数字进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1955646/