如何对整数和字符串数组进行排序?

How to sort an array of ints and strings?

我正在尝试对混合了整数和字符串的数组进行排序。举个例子:

a = ["a", "b", 5, "c", 4, "d", "a1", "a12", 3, 13, 2, "13a", "12a"]

我试过了:

a.sort do |x, y|
  if x.class == y.class
    x <=> y
  else
    x.class.to_s <=> y.class.to_s
  end
end

哪个returns:

[2, 3, 4, 5, 13, "12a", "13a", "a", "a1", "a12", "b", "c", "d"]

我想要的结果是:

[2, 3, 4, 5, "12a", 13, "13a", "a", "a1", "a12", "b", "c", "d"]
a.sort_by { |x| [(x.to_s.match(/^\d+/) ? x.to_i : 1.0 / 0), x.to_s] }

思路是先按数值排序,再按字符串值排序。如果字符串不是以数值开头,则强制认为数值为无穷大。


编辑:正如 OP 澄清的那样,他不仅要考虑前导数值,还要考虑后面的所有数值,我们可以使用相同的想法,只是这次我们有将其应用于字符串中每个单独的数字和 non-numeric 实体:

a.sort_by do |x|
  x.to_s.split(/(\D+)/).map do |y|
    [(y.match(/\d/) ? y.to_i : 1.0 / 0), y]
  end
end