How to split (chunk) a Ruby array into parts of X elements?

RubyArrays

Ruby Problem Overview


I have an array

foo = %w(1 2 3 4 5 6 7 8 9 10)

How can I split or "chunk" this into smaller arrays?

class Array
  def chunk(size)
    # return array of arrays
  end
end

foo.chunk(3)
# => [[1,2,3],[4,5,6],[7,8,9],[10]]

Ruby Solutions


Solution 1 - Ruby

Take a look at Enumerable#each_slice:

foo.each_slice(3).to_a
#=> [["1", "2", "3"], ["4", "5", "6"], ["7", "8", "9"], ["10"]]

Solution 2 - Ruby

If you're using rails you can also use in_groups_of:

foo.in_groups_of(3)

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
QuestionmačekView Question on Stackoverflow
Solution 1 - RubyMladen JablanovićView Answer on Stackoverflow
Solution 2 - RubyHeadView Answer on Stackoverflow