如何将数组的第二个字符串添加到同一个数组的第一个字符串ruby中

时间:2016-04-03 18:07:22

标签: arrays ruby

我有一系列城市和州。看起来像这样:

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

我最终想得到这个结果:

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

我这样做是为了测试:

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

结果得到了这个:

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

我正在尝试使用以下代码转换数组的其余部分,但将nil作为响应:

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

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:2)

关键是使用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"]