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?
You are looking for #each_slice.
data.each_slice(3) {|slice| ... }
Use .each_slice
[1,2,3,4,5,6,7,8,9,0].each_slice(3) {|a| p a}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With