Alex Rivera | Logout

Ruby array each_slice_with_index?

Asked 2011-05-12T20:20:41.073
48

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.

Edit
Report

1 Answer

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

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

answered 2012-02-13T21:02:00.910

Your Answer