Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split an array into some sub-arrays [duplicate]

Tags:

arrays

ruby

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.

like image 639
Zag zag.. Avatar asked Oct 19 '11 15:10

Zag zag..


People also ask

How do you split an array into 3 parts?

An efficient solution is to first find the sum S of all array elements. Check if this sum is divisible by 3 or not. This is because if sum is not divisible then the sum cannot be split in three equal sum sets. If there are three contiguous subarrays with equal sum, then sum of each subarray is S/3.


2 Answers

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]]
like image 128
Chris Ledet Avatar answered Oct 27 '22 22:10

Chris Ledet


check out the slice:

big_array.each_slice( 2 ).to_a
like image 33
tolitius Avatar answered Oct 28 '22 00:10

tolitius