Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate an array, n items at a time

Tags:

ruby

I have an array:

[1,2,3,4,5,6,7,8,9,0]  

that I'd like to iterate 3 at a time, which produces

1,2,3  and  4,5,6  and  7,8,9   and   0 

What's the best way to do this in Ruby?

like image 394
Carson Cole Avatar asked Oct 13 '12 03:10

Carson Cole


2 Answers

You are looking for #each_slice.

data.each_slice(3) {|slice| ... } 
like image 110
Chris Heald Avatar answered Sep 28 '22 02:09

Chris Heald


Use .each_slice

[1,2,3,4,5,6,7,8,9,0].each_slice(3) {|a| p a} 
like image 38
xdazz Avatar answered Sep 28 '22 00:09

xdazz