Class: Array

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

Overview

a method # that walks an array in groups, pass a block to call the block on each sub array

Instance Method Summary collapse

Instance Method Details

#in_groups_of(chunk_size, padded_with = nil, &block) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/mcollective/monkey_patches.rb', line 21

def in_groups_of(chunk_size, padded_with=nil, &block)
  arr = self.clone

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

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

  # 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_with_index do |a, i|
      case block.arity
        when 1
          yield(a)
        when 2
          yield(a, (i == result.size - 1))
        else
          raise "Expected 1 or 2 arguments, got #{block.arity}"
      end
    end
  else
    result
  end
end