Class: Array

Inherits:
Object
  • Object
show all
Defined in:
lib/core_ext/array/in_groups.rb

Instance Method Summary collapse

Instance Method Details

#in_groups(number, fill_with = nil) ⇒ Object

copied from ActiveSupport CoreExtensions



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/core_ext/array/in_groups.rb', line 4

def in_groups(number, fill_with = nil)
  # size / number gives minor group size;
  # size % number gives how many objects need extra accomodation;
  # each group hold either division or division + 1 items.
  division = size / number
  modulo = size % number

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

  number.times do |index|
    length = division + (modulo > 0 && modulo > index ? 1 : 0)
    padding = fill_with != false &&
      modulo > 0 && length == division ? 1 : 0
    groups << slice(start, length).concat([fill_with] * padding)
    start += length
  end

  if block_given?
    groups.each{|g| yield(g) }
  else
    groups
  end
end