class Array
Array
extentions.
Public Instance Methods
slice_by_size(size)
click to toggle source
Slice the array into sub-arrays of size n.
@return [Array<Array<Object>>] slices where each slice has approximately n items
If the array divides evenly then each slice has n items:
[1,2,3,4,5,6,7,8].slice_by_size(2) => [[1,2],[3,4],[5,6],[7,8]] [1,2,3,4,5,6,7,8].slice_by_size(4) => [[1,2,3,4],[5,6,7,8]]
If the array does not divide evenly then the last slice will be smaller:
[1,2,3,4,5,6,7,8].slice_by_size(3) => [[1,2,3],[4,5,6],[7,8]]
If the array size is small compared to n then the results will be best-attempt:
[1,2,3,4,5,6,7,8].slice_by_size(7) => [[1,2,3,4,5,6,7],[8]]
Compare slice_by_share
# File lib/sixarm_ruby_array_slice/array.rb, line 26 def slice_by_size(size) (size.is_a? Integer) or (raise ArgumentError, "size must be an integer") (size > 0) or (raise ArgumentError, "size must be > 0") arr=[] index=0 while index<length arr.push self[index...(index+size)] index+=size end return arr end