我有一个数组:
arr = ["Bar", "abc", "foo", "1", "20”, "10", "_def"]
我需要先使用不区分大小写的字母顺序排序,然后是数字,然后是特殊字符。
我正在尝试使用 sort_by
:
irb(main):071:0> arr.sort_by {|s| [s[/[0-9a-z]+/], s.to_i]}
=> ["1", "10", "20", "abc", "Bar", "_def", "foo"]
输出必须是:
arr = ["abc", "Bar", "foo", "1", “10”, “20", "_def"]
最佳答案
来自 docs :
Arrays are compared in an “element-wise” manner; the first element of
ary
is compared with the first one ofother_ary
using the<=>
operator, then each of the second elements, etc…
您可以通过创建排序组来利用此行为:
arr = ["Bar", "abc", "foo", "1", "20", "10", "_def"]
arr.sort_by do |s|
case s
when /^[a-z]/i
[1, s.downcase]
when /^\d/
[2, s.to_i]
else
[3, s]
end
end
#=> ["abc", "Bar", "foo", "1", "10", "20", "_def"]
第一个元素(1
、2
、3
)定义了组的位置:第一个位置是字母字符串,第二个位置是数字字符串,第三个位置是剩余的。在每个组中,元素按第二个元素排序:带字母的字符串按其小写值排序,数字字符串按其整数值排序,其余按自身排序。
关于ruby-on-rails - 如何使用 sort_by 按字母顺序排序,然后按数字排序,然后按特殊字符排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62622088/