I have an array:
array = [12, 13, 14, 18, 17, 19, 30, 23]
I need to split this array into arrays of maximum three elements each:
[12, 13, 14] [18, 17, 19] [30, 23]
How can I do this?
I have an array:
array = [12, 13, 14, 18, 17, 19, 30, 23]
I need to split this array into arrays of maximum three elements each:
[12, 13, 14] [18, 17, 19] [30, 23]
How can I do this?
Take a look at Enumerable#each_slice:
foo.each_slice(3).to_a
#=> [["1", "2", "3"], ["4", "5", "6"], ["7", "8", "9"], ["10"]]
If you're using rails you can also use in_groups_of:
foo.in_groups_of(3)
Try this...
Using Enumerable#each_slice
to slice array x value
array = [12, 13, 14, 18, 17, 19, 30, 23]
array.each_slice(3)
array.each_slice(3).to_a
By this time, I hope you got your answer. If you are using Rails, you can go with in_groups
, you won't have to call to_a
explicitly then :
array.in_groups(3)
# => [[12, 13, 14], [18, 17, 19], [30, 23, nil]]
array.in_groups(3, false)
# => [[12, 13, 14], [18, 17, 19], [30, 23]]
One more advantage of using in_groups
is, you can preserve the array size (strictly). It will fill_with
= nil
to maintain the array size.