56

Possible Duplicate:
Need to split arrays to sub arrays of specified size in Ruby

I'm looking to take an array---say [0,5,3,8,21,7,2] for example---and produce an array of arrays, split every so many places. If the above array were set to a, then

a.split_every(3)

would return [[0,5,3],[8,21,7][2]]

Does this exist, or do I have to implement it myself?

Community
  • 1
  • 1
invaliduser
  • 896
  • 1
  • 6
  • 9

2 Answers2

132

Use Enumerable#each_slice.

a.each_slice(3).to_a

Or, to iterate (and not bother with keeping the array):

a.each_slice(3) do |x,y,z|
  p [x,y,z]
end
Platinum Azure
  • 45,269
  • 12
  • 110
  • 134
  • 5
    Full credit to http://stackoverflow.com/questions/3864139/need-to-split-arrays-to-sub-arrays-of-specified-size-in-ruby, which taught me something new today :-) – Platinum Azure Oct 26 '11 at 18:52
22
a = (1..6).to_a
a.each_slice(2).to_a # => [[1, 2], [3, 4], [5, 6]]
a.each_slice(3).to_a # => [[1, 2, 3], [4, 5, 6]]
a.each_slice(4).to_a # => [[1, 2, 3, 4], [5, 6]]
maerics
  • 151,642
  • 46
  • 269
  • 291