If I have arr = [1, 2, 3, 4]
I know I can do the following...
如果我有arr =[1,2,3,4]我知道我可以做以下的…
> 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.
我知道我可以构建自己的数组方法。看看是否有一个内置函数来做这个。
3 个解决方案
#1
83
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:
与大多数迭代器方法一样,each_slice在没有块的情况下返回一个可枚举的值,因为ruby 1.8.7+之后,您可以在上面调用更多的可枚举方法。所以你能做什么:
arr.each_slice(2).with_index { |(a, b), i| puts "#{i} - #{a}, #{b}" }
#2
11
arr.each_slice(2).with_index { |(*a), i| ...
also note that the array, first parameter of the block, can be *arr
还要注意,数组的第一个参数,可以是*arr。
#3
6
In 1.9 a lot of methods return an enumerator if no block is provided. You can call another method on the enumerator.
在1.9中,如果没有提供块,许多方法会返回一个枚举数。您可以在枚举器上调用另一个方法。
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:
@sepp2k(变异)。结果:
0 - 1, 2
2 - 3, 4
4 - 5, 6
6 - 7, 8
#1
83
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:
与大多数迭代器方法一样,each_slice在没有块的情况下返回一个可枚举的值,因为ruby 1.8.7+之后,您可以在上面调用更多的可枚举方法。所以你能做什么:
arr.each_slice(2).with_index { |(a, b), i| puts "#{i} - #{a}, #{b}" }
#2
11
arr.each_slice(2).with_index { |(*a), i| ...
also note that the array, first parameter of the block, can be *arr
还要注意,数组的第一个参数,可以是*arr。
#3
6
In 1.9 a lot of methods return an enumerator if no block is provided. You can call another method on the enumerator.
在1.9中,如果没有提供块,许多方法会返回一个枚举数。您可以在枚举器上调用另一个方法。
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:
@sepp2k(变异)。结果:
0 - 1, 2
2 - 3, 4
4 - 5, 6
6 - 7, 8