Ruby通过分组和按数字排序来对数组进行排序
给定一个数组,如
['b1','a2','a3','b2','a1','b3']
我如何对其进行排序,以便按字母“a”或“b”进行分组,然后按出现的数字的顺序对它们进行排序。例如。
['a1','a2','a3','b1','b2','b3']
或更复杂的例子:
['fb15', 'abc51', 'abc30', 'fb12']
排序为:
['abc30', 'abc51', 'fb12', 'fb15']
所以假设我可以拥有一大群不同的“标签”,比如狗。猫,熊,猫头鹰。这些都在数组中出现多次,每次后跟一个数字。
只是我想对它们进行分组,然后按数字排序。
回答
在 Ruby 中,数组按字典顺序排列。这意味着,每当您需要按主键、次要键、第三键、……排序键订购某物时,您只需将项目转换为数组即可。
ary.sort_by do |el|
str, num = el.partition(/p{Digit}+/)
[str, num.to_i]
end
- Small issue because of the capture groups `scan` is going to return `[['a','1']]` which means that the destructuring sets `str` to the inner Array and `num` to `nil`.You could go with `str, num = el.partition(/p{Digit}+/)` instead.