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?
The array_chunk() function splits an array into chunks of new arrays.
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.
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
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]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With