Sha*_*uno 1 ruby arrays enumerable
我正在寻找最有效的方法来做到这一点。任何带连字符的内容都必须位于数组中任何不带连字符的符号之前。我的天真的解决方案对数组进行两次过滤并连接。我觉得应该有一种方法可以一次而不是两次完成此任务。
input = [:en, :de, :es, :"es-MX", :fr, :ko, :"ko-KR", :"en-GB"]
output = [:"es-MX", :"ko-KR", :"en-GB", :en, :de, :es, :fr]
Run Code Online (Sandbox Code Playgroud)
天真的解决方案:
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
Run Code Online (Sandbox Code Playgroud)
这是一项排序任务,因此对我来说最有意义的是简单地使用Enumerable#sort_by:
# Put symbols with hyphens first
input.sort_by { |s| s.to_s.include?('-') ? 0 : 1 }
Run Code Online (Sandbox Code Playgroud)
如果您想按这些类别中的其他内容进行排序,您可以执行以下操作:
# Put symbols with hyphens first, then sort in alphabetical order
input.sort_by { |s| [s.to_s.include?('-') ? 0 : 1, s] }
Run Code Online (Sandbox Code Playgroud)