8

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

I would like to split an array into an array of sub-arrays.

For example,

big_array = (0...6).to_a

How can we cut this big array into an array of arrays (of a max length of 2 items) such as:

arrays = big_array.split_please(2)

Where...

arrays # => [ [0, 1],
              [2, 3],
              [4, 5] ]

Note: I ask this question, 'cause in order to do it, I'm currently coding like this:

arrays = [
           big_array[0..1],
           big_array[2..3],
           big_array[4..5]
         ]

...which is so ugly. And very unmaintainable code, when big_array.length > 100.

Community
  • 1
  • 1
Zag zag..
  • 6,041
  • 6
  • 27
  • 36

2 Answers2

16

You can use the #each_slice method on the array

big_array = (0..20).to_a
array = big_array.each_slice(2).to_a
puts array # [[0, 1], [2, 3], [4, 5], [6, 7], [8, 9], [10, 11], [12, 13], [14, 15], [16, 17], [18, 19], [20]]
Chris Ledet
  • 11,458
  • 7
  • 39
  • 47
6

check out the slice:

big_array.each_slice( 2 ).to_a
tolitius
  • 22,149
  • 6
  • 70
  • 81