What's the 'Ruby way' to iterate over two arrays at once

Viewed 60649

More of a syntax curiosity than a problem to solve...

I have two arrays of equal length, and want to iterate over them both at once - for example, to output both their values at a certain index.

@budget = [ 100, 150, 25, 105 ]
@actual = [ 120, 100, 50, 100 ]

I know that I can use each_index and index into the arrays like so:

@budget.each_index do |i|
  puts @budget[i]
  puts @actual[i]
end

Is there a Ruby way to do this better? Something like this?

# Obviously doesn't achieve what I want it to - but is there something like this?
[@budget, @actual].each do |budget, actual|
  puts budget
  puts actual
end
7 Answers
Related