Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split array up into n-groups of m size? [duplicate]

Tags:

arrays

ruby

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?

like image 771
invaliduser Avatar asked Oct 26 '11 18:10

invaliduser


People also ask

Which function is used to divide an array into smaller evenly size arrays?

The array_chunk() function splits an array into chunks of new arrays.

How do you subdivide an array in Java?

Using the copyOfRange() method you can copy an array within a range. This method accepts three parameters, an array that you want to copy, start and end indexes of the range. You split an array using this method by copying the array ranging from 0 to length/2 to one array and length/2 to length to other.


2 Answers

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
like image 193
Platinum Azure Avatar answered Oct 21 '22 20:10

Platinum Azure


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]]
like image 21
maerics Avatar answered Oct 21 '22 21:10

maerics