Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can you loop through multiple arrays parallel?

Tags:

ruby

i have 4 arrays.

["one", "two", "three"]
["1", "2", "3"
["un", "deux", "trois"]
["ichi", "ni", "san"]

is it possible to concatenate each element in their respective arrays ?

so i end up with single lines of string like like

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

and so on...

is it possible to do this in one loop ?

for i in (1..array1.count)

puts array1[i] + ", " + array2[i] + ", " + array3[i] + ", " + array4[i]

end

What happens when there might be unpredictable number of arrays & they are each unequal size?

like image 986
gqweg Avatar asked Oct 21 '09 02:10

gqweg


2 Answers

Easy:

a = [array1,array2,array3,array4] # or however many you have

puts a.transpose.map {|x| x.join(", ")}.join("\n")

This will work with any number of subarrays as long as they are all the same size (regardless of what that size is).

If the subarrays are different lengths, but it's OK to use the length of the first one, you can do this:

a[0].zip(*a[1..-1]).map {|x| x.join(", ")}.join("\n")
like image 170
glenn mcdonald Avatar answered Sep 28 '22 18:09

glenn mcdonald


Well if you know that they were all the same length:

(0...array1.length).each{|i|puts array1[i] + ", " + array2[i] + ", " + array3[i] + ", " + array4[i]}

Edit: The Following code works

array1 = ["one", "two", "three"]
array2 = ["1", "2", "3"]
array3 = ["un", "deux", "trois"]
array4 = ["ichi", "ni", "san"]

(0...array1.length).each{|i| puts array1[i] + ", " + array2[i] + ", " + array3[i] + ", " + array4[i]}

Edit2: what happens if you dont know how many arrays there will be?

I would suggest making an array of arrays; a list of arrays. Make an array of arrays (essentially a 2D array but it can't be indexed like one) and with it print every line one by one for each array in the arrayList.

This code works:

array1 = ["one", "two", "three"]
array2 = ["1", "2", "3"]
array3 = ["un", "deux", "trois"]
array4 = ["ichi", "ni", "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"
}
like image 20
Robert Massaioli Avatar answered Sep 28 '22 16:09

Robert Massaioli