Iterate an array, n items at a time

Ruby

Ruby Problem Overview


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?

Ruby Solutions


Solution 1 - Ruby

You are looking for #each_slice.

data.each_slice(3) {|slice| ... }

Solution 2 - Ruby

Use .each_slice

[1,2,3,4,5,6,7,8,9,0].each_slice(3) {|a| p a}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCarson ColeView Question on Stackoverflow
Solution 1 - RubyChris HealdView Answer on Stackoverflow
Solution 2 - RubyxdazzView Answer on Stackoverflow