I have an array that is something like this:
arr = [4, 5, 6, 7, 8, 4, 45, 11]
I want a fancy method like
sub_arrays = split (arr, 3)
This should return the following: [[4, 5, 6], [7,8,4], [45,11]]
Note: This question is not a duplicate of "How to chunk an array". The chunk question is asking about processing in batches and this question is about splitting arrays.
arr.each_slice(3).to_a
each_slice
returns an Enumerable, so if that's enough for you, you don't need to call to_a
.
In 1.8.6 you need to do:
require 'enumerator' arr.enum_for(:each_slice, 3).to_a
If you just need to iterate, you can simply do:
arr.each_slice(3) do |x,y,z| puts(x+y+z) end
can also utilize this with a specific purpose:
((1..10).group_by {|i| i%3}).values #=> [[1, 4, 7, 10], [2, 5, 8], [3, 6, 9]]
in case you just want two partitioned arrays:
(1..6).partition {|v| v.even? } #=> [[2, 4, 6], [1, 3, 5]]
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