Ruby array each_slice_with_index?

情到浓时终转凉″ 提交于 2019-12-02 19:54:03

Like most iterator methods, each_slice returns an enumerable when called without a block since ruby 1.8.7+, which you can then call further enumerable methods on. So you can do:

arr.each_slice(2).with_index { |(a, b), i| puts "#{i} - #{a}, #{b}" }
arr.each_slice(2).with_index { |(*a), i| ...

also note that the array, first parameter of the block, can be *arr

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!