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?
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,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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With