简体   繁体   中英

How can I add the second string of an array to the first string of the same array, ruby

I have an array of cities and states. Looks something like this:

locations = ["Colorado Springs","CO","Denver","CO","Kissimmee","FL","Orlando", "FL"]

I would ultimately like to get this result:

locations = ["Colorado Springs, CO","CO","Denver, CO","CO","Kissimmee, FL","FL","Orlando, FL", "FL"]

I did this to test:

locations[0] << ", #{locations[1]}"

And got this as a result:

locations = ["Colorado Springs, CO", "CO", "Denver", "CO", "Kissimmee", "FL", "Orlando", "FL"]

I am attempting the code below to convert the rest of the array but getting nil as a response:

locations = ["Colorado Springs","CO","Denver","CO","Kissimmee","FL","Orlando", "FL"]

counter0 = 0
counter1 = 1 

while counter0 < locations.length
  locations[counter0] << locations[counter1]
  counter0 += 2 
  counter1 += 2
end 

=> nil
locations.each_slice(2).flat_map { |city, state| ["#{city}, #{state}", state] }
  #=> ["Colorado Springs, CO", "CO", "Denver, CO", "CO",
  #    "Kissimmee, FL", "FL", "Orlando, FL", "FL"] 

The key is to use flat_map .

locations.each_slice(2).flat_map{|x, y| [[x, y].join(", "), y]}
# => ["Colorado Springs, CO", "CO", "Denver, CO", "CO", "Kissimmee, FL", "FL", "Orlando, FL", "FL"]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM