Puppet Function: choria::in_groups_of

Defined in:
lib/puppet/functions/choria/in_groups_of.rb
Function type:
Ruby 4.x API

Overview

choria::in_groups_of(Array $items, Integer $size, Callable &$block)Any

Loops over an array calling the supplied block for sub groups of it

This will produce the following output:

Notice: Scope(Class[main]): [1, 2, 3]
Notice: Scope(Class[main]): [4, 5, 6]
Notice: Scope(Class[main]): [7, 8, 9]
Notice: Scope(Class[main]): [10]

When the items are not evenly devisable by the provided size no padding will be done on the final yield to your lambda as shown above

Examples:

count to 10 in groups of 3


[1, 2, 3, 4, 5, 6, 7, 8, 9, 0].choria::in_groups_of(3) |$grp| {
  notice($grp)
}

Parameters:

  • items (Array)
  • size (Integer)
  • &block (Callable)

Returns:

  • (Any)


18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/puppet/functions/choria/in_groups_of.rb', line 18

Puppet::Functions.create_function(:"choria::in_groups_of") do
  dispatch :handler do
    param "Array", :items
    param "Integer", :size
    block_param
  end

  def handler(items, chunk_size)
    arr = items.clone

    count = (arr.size / Float(chunk_size)).ceil

    groups = []
    
    results = []

    count.times {|s| groups <<  arr[s * chunk_size, chunk_size]}

    groups.each_with_index do |a|
      results << yield(a)
    end

    results
  end
end