Ruby – What’s the ‘Ruby way’ to iterate over two arrays at once

arraysiteratorruby

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

Best Answer

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

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

>> @budget.zip(@actual).each do |budget, actual|
?>   puts budget
>>   puts actual
>> end
100
120
150
100
25
50
105
100
=> [[100, 120], [150, 100], [25, 50], [105, 100]]