-1

I have an array:

array = [12, 13, 14, 18, 17, 19, 30, 23]

I need to split this array into arrays of maximum three elements each:

[12, 13, 14] [18, 17, 19] [30, 23]

How can I do this?

sawa
  • 165,429
  • 45
  • 277
  • 381
David Geismar
  • 3,152
  • 6
  • 41
  • 80
  • 1
    This question has already been asked. Here is a link to it: http://stackoverflow.com/questions/2699584/how-to-split-chunk-a-ruby-array-into-parts-of-x-elements – Sari Rahal Jun 11 '15 at 12:14

3 Answers3

1

Take a look at Enumerable#each_slice:

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

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

foo.in_groups_of(3)
Sari Rahal
  • 1,897
  • 2
  • 32
  • 53
1

Try this... Using Enumerable#each_slice to slice array x value

array  = [12, 13, 14, 18, 17, 19, 30, 23]
array.each_slice(3)
array.each_slice(3).to_a 
Deenadhayalan Manoharan
  • 5,436
  • 14
  • 30
  • 50
0

By this time, I hope you got your answer. If you are using Rails, you can go with in_groups, you won't have to call to_a explicitly then :

array.in_groups(3)
# => [[12, 13, 14], [18, 17, 19], [30, 23, nil]]

array.in_groups(3, false)
# => [[12, 13, 14], [18, 17, 19], [30, 23]]

One more advantage of using in_groups is, you can preserve the array size (strictly). It will fill_with = nil to maintain the array size.

Sharvy Ahmed
  • 7,247
  • 1
  • 33
  • 46