I have an array:
arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
I want to split arr1 into x slices, where each slice is as full and equal as possible.
arr2 = arr1.foo(3)
# => [1, 2, 3, 4][5, 6, 7][8, 9, 10]
each_slice does the opposite of what I want, separating the array into groups of x elements instead.
arr2 = arr1.each_slice(3)
# => [1, 2, 3][4, 5, 6][7, 8, 9][10]
If possible, I want to do this without using rails-specific methods like in_groups.
class Array
def in_groups(n)
len, rem = count.divmod(n)
(0...n).map { | i | (i < rem) ? self[(len+1) * i, len + 1] : self[len * i + rem, len] }
end
end
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