5 module Puppet::Parser::Functions
6 newfunction(:values_at, :type => :rvalue, :doc => <<-EOS
7 Finds value inside an array based on location.
9 The first argument is the array you want to analyze, and the second element can
12 * A single numeric index
13 * A range in the form of 'start-stop' (eg. 4-9)
14 * An array combining the above
18 values_at(['a','b','c'], 2)
22 values_at(['a','b','c'], ["0-1"])
24 Would return ['a','b'].
26 values_at(['a','b','c','d','e'], [0, "2-3"])
28 Would return ['a','c','d'].
32 raise(Puppet::ParseError, "values_at(): Wrong number of " +
33 "arguments given (#{arguments.size} for 2)") if arguments.size < 2
35 array = arguments.shift
37 unless array.is_a?(Array)
38 raise(Puppet::ParseError, 'values_at(): Requires array to work with')
41 indices = [arguments.shift].flatten() # Get them all ... Pokemon ...
43 if not indices or indices.empty?
44 raise(Puppet::ParseError, 'values_at(): You must provide ' +
45 'at least one positive index to collect')
53 if m = i.match(/^(\d+)(\.\.\.?|\-)(\d+)$/)
60 raise(Puppet::ParseError, 'values_at(): Stop index in ' +
61 'given indices range is smaller than the start index')
62 elsif stop > array.size - 1 # First element is at index 0 is it not?
63 raise(Puppet::ParseError, 'values_at(): Stop index in ' +
64 'given indices range exceeds array size')
68 when /^(\.\.|\-)$/ then (start .. stop)
69 when /^(\.\.\.)$/ then (start ... stop) # Exclusive of last element ...
72 range.each { |i| indices_list << i.to_i }
74 # Only positive numbers allowed in this case ...
75 if not i.match(/^\d+$/)
76 raise(Puppet::ParseError, 'values_at(): Unknown format ' +
80 # In Puppet numbers are often string-encoded ...
83 if i > array.size - 1 # Same story. First element is at index 0 ...
84 raise(Puppet::ParseError, 'values_at(): Given index ' +
92 # We remove nil values as they make no sense in Puppet DSL ...
93 result = indices_list.collect { |i| array[i] }.compact
99 # vim: set ts=2 sw=2 et :