我有4个阵列.
["one","two","three"] ["1","2","3" ["un","deux","trois"] ["ichi","ni","san"]
是否可以在各自的数组中连接每个元素?
所以我最终会得到像单行一样的字符串
"one,1,un,ichi"\n "two,2,deux,ni"\n
等等…
是否可以在一个循环中执行此操作?
for i in (1..array1.count) puts array1[i] + "," + array2[i] + "," + array3[i] + "," + array4[i] end
当可能存在不可预测的阵列数量时会发生什么?它们各自的大小不一样?
解决方法
好吧,如果你知道他们都是相同的长度:
(0...array1.length).each{|i|puts array1[i] + "," + array4[i]}
编辑:以下代码有效
array1 = ["one","three"] array2 = ["1","3"] array3 = ["un","trois"] array4 = ["ichi","san"] (0...array1.length).each{|i| puts array1[i] + "," + array4[i]}
编辑2:如果您不知道将有多少阵列会发生什么?
我建议制作一个数组数组;数组列表.创建一个数组数组(本质上是一个2D数组,但不能像一个数组一样索引),并使用它为arrayList中的每个数组逐个打印每一行.
此代码有效:
array1 = ["one","san"] arrayList = [] arrayList.push(array1,array2,array3,array4) p arrayList (0...array1.length).each{|i| (0...arrayList.length).each{|j| print arrayList[j][i] + "," } print "\n" }