Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to iterate three arrays at the same time?

We can iterate two arrays at the same time using Array's zip method like:

@budget.zip(@actual).each do |budget, actual|
  ...
end

Is it possible to iterate three arrays? Can we use the transpose method to do the same?

like image 258
Hrishikesh Sardar Avatar asked Jun 12 '13 15:06

Hrishikesh Sardar


People also ask

Is it possible to iterate over arrays?

Iterating over an arrayYou can iterate over an array using for loop or forEach loop. Using the for loop − Instead on printing element by element, you can iterate the index using for loop starting from 0 to length of the array (ArrayName. length) and access elements at each index.


1 Answers

>> [1,2,3].zip(["a","b","c"], [:a,:b,:c]) { |x, y, z| p [x, y, z] }
[1, "a", :a]
[2, "b", :b]
[3, "c", :c]

transpose also works but, unlike zip, it creates a new array right away:

>> [[1,2,3], ["a","b","c"], [:a,:b,:c]].transpose.each { |x, y, z| p [x, y, z] }
[1, "a", :a]
[2, "b", :b]
[3, "c", :c]

Notes:

  • You don't need each with zip, it takes a block.

  • Functional expressions are also possible. For example, using map: sums = xs.zip(ys, zs).map { |x, y, z| x + y + z }.

  • For an arbitrary number of arrays you can do xss[0].zip(*xss[1..-1]) or simply xss.transpose.

like image 194
tokland Avatar answered Sep 30 '22 21:09

tokland