【发布时间】:2016-04-21 04:48:35
【问题描述】:
我正在尝试对包含整数和字符串的数组进行排序。举个例子:
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
返回:
[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"]
【问题讨论】:
-
字符串中可以有多个数字,例如
"a1b2c3"? -
什么是正确的?
["a1", "a12", "a2"]或["a1", "a2", "a12"]? -
@Stefan 字符串中可能有多个数字。后者
["a1", "a2", "a12"] -
@ChristianFazzini,即使在字符串中有多个数字的情况下,更新版本也可以工作。看看吧。
标签: arrays ruby sorting natural-sort