我有两个阵列
names = ["name1", "name2"]
tracks = ["track1", "track2"]
我想把这两个数组合并成一个新数组
data => ["name1 track1", "name2 track2"]
我试了一下
1) @data = @name.zip(@tracks)flatten
produces ["name1", "track1", "name2", "track2"]
2) @data = @name.at(0).concat(@tracks.at(0)) + @name.at(1).concat(@tracks.at(1))
produces ["name1track1name2track2"]
3) @name.each do |n|
@tracks.each do |t|
@data.push n + " " + t
end
end
produces ["name1 track1", "name1 track2", "name2 track1", "name2 track2"]
我似乎解决不了这个问题我很感激你的帮助。
最佳答案
names = ["name1", "name2"] #note the "="
tracks = ["track1", "track2"]
p names.zip(tracks).map{|e| e.join(" ")}
#=> ["name1 track1", "name2 track2"]
关于ruby - 合并来自两个单独数组的字符串元素,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21912357/