Class: ReeArray::InGroupsOf

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

Instance Method Summary collapse

Instance Method Details

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



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

def call(array, number, **opts, &block)
  if number.to_i <= 0
    raise ArgumentError,
      "Group size must be a positive integer, was #{number.inspect}"
  end

  collection = if opts.has_key?(:fill_with)
    # size % number gives how many extra we have;
    # subtracting from number gives how many to add;
    # modulo number ensures we don't add group of just fill.
    padding = (number - array.size % number) % number
    array.dup.concat(Array.new(padding, opts[:fill_with]))
  else
    array
  end

  if block_given?
    collection.each_slice(number, &block)
  else
    collection.each_slice(number).to_a
  end
end