views:

91

answers:

2

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
+6  A: 

Use the Array.zip method and pass it a block to iterate over the corresponding elements sequentially.

Anurag
+12  A: 
>> @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]]
gnibbler
'.each' can unfold array elements? I wonder how much more of Ruby I don't know :/
Nikita Rybak
I love Ruby! :)
nfm
If you're going to use an expression like that, it's always best to use parentheses for method calls, just in case. @budget.zip(@actual).each
AboutRuby
@AboutRuby: In this case, it's needed! Fixed.
Marc-André Lafortune
@AboutRuby, Marc-André, ah yes it's needed for 1.8, not for 1.9 though. Better to have the answer work for both though, I agree
gnibbler