如何优雅地组合和格式化Ruby数组?

时间:2019-07-17 18:49:40

标签: arrays ruby formatting

我有一系列国家和州列表。当我看到州列表时,我想将其与该国家/地区合并在一起,然后再加上括号。

数组示例: ["United Kingdom",[],"United States", ["Arkansas","Massachusetts","Alaska"],"China",[]]

我想将数组格式化为 ["United Kingdom", "United States (Arkansas, Massachusetts, Alaska)", "China"]

1 个答案:

答案 0 :(得分:1)

def pretty_format arr
   arr.each_slice(2).map do |country, states|
     "#{country}#{states.length > 0 ? ' (' + states.join(', ') +')': ''}"
   end
end

pretty_format ["United Kingdom", [], "United States",
  ["Arkansas", "Massachusetts","Alaska"],"China",[]]
  #=> ["United Kingdom", "United States (Arkansas, Massachusetts, Alaska)",
  #    "China"]