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?
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?
>> [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
.