Ruby数组each_slice_with_index? [英] Ruby array each_slice_with_index?
本文介绍了Ruby数组each_slice_with_index?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有 arr = [1,2,3,4]
我知道我可以执行以下操作...
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
...而且......
...And...
> arr.each_with_index { |x, i| puts "#{i} - #{x}" }
0 - 1
1 - 2
2 - 3
3 - 4
...但是有内置的方法吗?
...But is there a built in way to do this?
> arr.each_slice_with_index(2) { |i, a, b| puts "#{i} - #{a}, #{b}" }
0 - 1, 2
2 - 3, 4
我知道我可以构建自己的并将其粘贴到数组方法中。只是想查看是否有内置函数来执行此操作。
I know I can built my own and stick it into the array method. Just looking to see if there is a built in function to do this.
推荐答案
与大多数迭代器方法一样, each_slice
返回一个可枚举的枚举,因为ruby 1.8.7+之后没有块,你可以调用更多的可枚举方法。所以你可以这样做:
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}" }
这篇关于Ruby数组each_slice_with_index?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文