Hi,
I have an array 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 me [[4, 5, 6], [7,8,4], [45,11]]
Hi,
I have an array 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 me [[4, 5, 6], [7,8,4], [45,11]]
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