Ruby按字母排序数组[关闭]

问题描述 投票:-7回答:2

我有Array,其中包含混合数据。

就像是

["AB_1020", "AB_950", "AB_50", "1000", "570"]

输出应该是

AB_50, AB_950, AB_1020, 570, 1000
ruby-on-rails arrays ruby sorting alphabetical
2个回答
2
投票
["AB_1020", "AB_950", "AB_50", "1000", "570"].sort_by do |k|
  i, w = k.split('_').rotate
  [w.to_s, -i.to_i]
end.reverse
#⇒ ["AB_50", "AB_950", "AB_1020", "570", "1000"]

2
投票

你可以做这样的事情

p ["AB_1020", "AB_950", "AB_50", "1000", "570"].partition{|x| x.to_i.zero? }
      .flat_map{|x| x.sort_by {|x|x[/d+/]}.reverse}

产量

#⇒ ["AB_50", "AB_950", "AB_1020", "570", "1000"]
© www.soinside.com 2019 - 2024. All rights reserved.