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