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

后端 未结 7 446
别跟我提以往
别跟我提以往 2020-12-04 05:52

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 the

7条回答
  •  长情又很酷
    2020-12-04 06:22

    >> @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]]
    

提交回复
热议问题