我有一系列国家和州列表。当我看到州列表时,我想将其与该国家/地区合并在一起,然后再加上括号。
数组示例:
["United Kingdom",[],"United States", ["Arkansas","Massachusetts","Alaska"],"China",[]]
我想将数组格式化为
["United Kingdom", "United States (Arkansas, Massachusetts, Alaska)", "China"]
答案 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"]