| Class | Array |
| In: |
lib/mcollective/monkey_patches.rb
|
| Parent: | Object |
a method # that walks an array in groups, pass a block to call the block on each sub array
# File lib/mcollective/monkey_patches.rb, line 29
29: def in_groups_of(chunk_size, padded_with=nil, &block)
30: arr = self.clone
31:
32: # how many to add
33: padding = chunk_size - (arr.size % chunk_size)
34:
35: # pad at the end
36: arr.concat([padded_with] * padding) unless padding == chunk_size
37:
38: # how many chunks we'll make
39: count = arr.size / chunk_size
40:
41: # make that many arrays
42: result = []
43: count.times {|s| result << arr[s * chunk_size, chunk_size]}
44:
45: if block_given?
46: result.each_with_index do |a, i|
47: case block.arity
48: when 1
49: yield(a)
50: when 2
51: yield(a, (i == result.size - 1))
52: else
53: raise "Expected 1 or 2 arguments, got #{block.arity}"
54: end
55: end
56: else
57: result
58: end
59: end