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 21 21: def in_groups_of(chunk_size, padded_with=nil, &block) 22: arr = self.clone 23: 24: # how many to add 25: padding = chunk_size - (arr.size % chunk_size) 26: 27: # pad at the end 28: arr.concat([padded_with] * padding) unless padding == chunk_size 29: 30: # how many chunks we'll make 31: count = arr.size / chunk_size 32: 33: # make that many arrays 34: result = [] 35: count.times {|s| result << arr[s * chunk_size, chunk_size]} 36: 37: if block_given? 38: result.each_with_index do |a, i| 39: case block.arity 40: when 1 41: yield(a) 42: when 2 43: yield(a, (i == result.size - 1)) 44: else 45: raise "Expected 1 or 2 arguments, got #{block.arity}" 46: end 47: end 48: else 49: result 50: end 51: end