Class: Array

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

Instance Method Summary collapse

Instance Method Details

#in_groups_of(chunk_size, padded_with = nil) ⇒ Object



2
3
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
29
30
31
32
# File 'lib/gdash/monkey_patches.rb', line 2

def in_groups_of(chunk_size, padded_with=nil)
  if chunk_size <= 1
    if block_given?
      self.each{|a| yield([a])}
    else
      self
    end
  else
    arr = self.clone

    # how many to add
    padding = chunk_size - (arr.size % chunk_size)
    padding = 0 if padding == chunk_size

    # pad at the end
    arr.concat([padded_with] * padding)

    # how many chunks we'll make
    count = arr.size / chunk_size

    # make that many arrays
    result = []
    count.times {|s| result <<  arr[s * chunk_size, chunk_size]}

    if block_given?
      result.each{|a| yield(a)}
    else
      result
    end
  end
end