Class: Array

Inherits:
Object
  • Object
show all
Defined in:
lib/sixarm_ruby_array_slice.rb

Instance Method Summary collapse

Instance Method Details

#slice_by_share(share) ⇒ Array<Array<Object>>

Slice the array into n sub-arrays of the same size.

If the array divides evenly, then each slice has size/n items:

[1,2,3,4,5,6,7,8].slice_by_share(2) => [[1,2,3,4],[5,6,7,8]]
[1,2,3,4,5,6,7,8].slice_by_share(4) => [[1,2],[3,4],[5,6],[7,8]]

If the array does not divide evenly then the latter slices will be smaller:

[1,2,3,4,5,6,7,8].slice_by_share(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_share(7) => [[1,2],[3,4],[5,6],[7,8],[],[],[]]

Compare #slice_by_size



61
62
63
64
65
66
67
# File 'lib/sixarm_ruby_array_slice.rb', line 61

def slice_by_share(share)
  (share.is_a? Integer) or (raise ArgumentError, "share must be an integer")
  (share > 0) or (raise ArgumentError, "share must be > 0")
  arr = slice_by_size((length.to_f/share.to_f).ceil)
  while arr.size < share do arr << [] end
  return arr
end

#slice_by_size(size) ⇒ Array<Array<Object>>

Slice the array into sub-arrays of size n.

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



29
30
31
32
33
34
35
36
37
38
39
# File 'lib/sixarm_ruby_array_slice.rb', line 29

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