Class: ReeArray::InGroups

Inherits:
Object
  • Object
show all
Includes:
Ree::FnDSL
Defined in:
lib/ree_lib/packages/ree_array/package/ree_array/functions/in_groups.rb

Instance Method Summary collapse

Instance Method Details

#call(array, number, **opts, &block) ⇒ Object


33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/ree_lib/packages/ree_array/package/ree_array/functions/in_groups.rb', line 33

def call(array, number, **opts, &block)
  # size.div number gives minor group size;
  # size % number gives how many objects need extra accommodation;
  # each group hold either division or division + 1 items.
  division = array.size.div(number)
  modulo = array.size % number

  # create a new array avoiding dup
  groups = []
  start = 0

  number.times do |index|
    length = division + (modulo > 0 && modulo > index ? 1 : 0)
    groups << last_group = array.slice(start, length)

    if opts.has_key?(:fill_with) && modulo > 0 && length == division
      last_group << opts[:fill_with]
    end

    start += length
  end

  if block_given?
    groups.each(&block)
  else
    groups
  end
end