Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby array each_slice_with_index?

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.

like image 756
Drew Avatar asked May 12 '11 20:05

Drew


3 Answers

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}" }
like image 197
sepp2k Avatar answered Nov 18 '22 13:11

sepp2k


arr.each_slice(2).with_index { |(*a), i| ...

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

like image 11
mekdigital Avatar answered Nov 18 '22 14:11

mekdigital


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
like image 6
steenslag Avatar answered Nov 18 '22 13:11

steenslag