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

后端 未结 7 443
别跟我提以往
别跟我提以往 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:18

    Simply zipping the two arrays together works well if you are dealing with arrays. But what if you are dealing with never-ending enumerators, such as something like these:

    enum1 = (1..5).cycle
    enum2 = (10..12).cycle
    

    enum1.zip(enum2) fails because zip tries to evaluate all the elements and combine them. Instead, do this:

    enum1.lazy.zip(enum2)
    

    That one lazy saves you by making the resulting enumerator lazy-evaluate.

提交回复
热议问题