rdog
rdog

Reputation: 13

How to elegantly combine and format an Ruby array?

I have an array of countries and lists of states. When I see a state list, I want to combine that with the country just before it with parentheses.

Example array: ["United Kingdom",[],"United States", ["Arkansas","Massachusetts","Alaska"],"China",[]]

I want to format the array into ["United Kingdom", "United States (Arkansas, Massachusetts, Alaska)", "China"]

Upvotes: 0

Views: 116

Answers (1)

bsam
bsam

Reputation: 930

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"]

Upvotes: 1

Related Questions