Ruby array each_slice_with_index?

前端 未结 3 1675
野趣味
野趣味 2021-02-01 13:30

If I have arr = [1, 2, 3, 4] I know I can do the following...

> arr.each_slice(2) { |a, b| puts \"#{a}, #{b}\" }
1, 2
3, 4

...A

3条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-01 13:50

    In 1.9 a lot of methods return an enumerator if no block is provided. You can call another method on the enumerator.

    arr = [1, 2, 3, 4, 5, 6, 7, 8] 
    arr.each_with_index.each_slice(2){|(a,i), (b,j)| puts "#{i} - #{a}, #{b}"}
    

    (Variation on @sepp2k). Result:

    0 - 1, 2
    2 - 3, 4
    4 - 5, 6
    6 - 7, 8
    

提交回复
热议问题