class Array

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

Public Instance Methods

in_groups_of(chunk_size, padded_with=nil) { |a| ... } click to toggle source
# File plugins/mcollective/application/inventory.rb, line 7
def in_groups_of(chunk_size, padded_with=nil)
    arr = self.clone

    # how many to add
    padding = chunk_size - (arr.size % 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