我有一系列城市和州。看起来像这样:
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
答案 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"]