【发布时间】:2022-01-17 07:58:53
【问题描述】:
我正在寻找最有效的方法来做到这一点。任何带有连字符的东西都必须在数组中任何不带连字符的符号之前。我天真的解决方案过滤数组两次并连接。我觉得应该有一种方法可以一次完成,而不是两次。
input = [:en, :de, :es, :"es-MX", :fr, :ko, :"ko-KR", :"en-GB"]
output = [:"es-MX", :"ko-KR", :"en-GB", :en, :de, :es, :fr]
天真的解决方案:
def reorder(input)
## find everything with a hypen
output = input.select { |l|
l.to_s.include?('-')
}
# find everything without a hyphen and concat to output
output.concat(input.reject { |l|
l.to_s.include?('-')
})
end
【问题讨论】:
-
如果对带和不带连字符的符号顺序没有限制,您可以编写以下内容:
[:en, :de, :es, :"es-MX", :fr, :ko, :"ko-KR", :"en-GB"].each_with_object([]) { |sym, arr| sym.to_s.include?('-') ? arr.unshift(sym) : arr << sym } #=> [:"en-GB", :"ko-KR", :"es-MX", :en, :de, :es, :fr, :ko]。我看到这是@Balastrong 答案的变体。
标签: arrays ruby enumerable