ruby – 如何在多个数组之间并行循环?

前端之家收集整理的这篇文章主要介绍了ruby – 如何在多个数组之间并行循环?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有4个阵列. @H_404_2@["one","two","three"] ["1","2","3" ["un","deux","trois"] ["ichi","ni","san"]

是否可以在各自的数组中连接每个元素?

所以我最终会得到像单行一样的字符串

@H_404_2@"one,1,un,ichi"\n "two,2,deux,ni"\n

等等…

是否可以在一个循环中执行此操作?

@H_404_2@for i in (1..array1.count) puts array1[i] + "," + array2[i] + "," + array3[i] + "," + array4[i] end

当可能存在不可预测的阵列数量时会发生什么?它们各自的大小不一样?

解决方法

好吧,如果你知道他们都是相同的长度: @H_404_2@(0...array1.length).each{|i|puts array1[i] + "," + array4[i]}

编辑:以下代码有效

@H_404_2@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中的每个数组逐个打印每一行.

代码有效:

@H_404_2@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" }
原文链接:https://www.f2er.com/ruby/270452.html

猜你在找的Ruby相关文章