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')
52 if m = i.match(/^(\d+)(\.\.\.?|\-)(\d+)$/)
59 raise(Puppet::ParseError, 'values_at(): Stop index in ' +
60 'given indices range is smaller than the start index')
61 elsif stop > array.size - 1 # First element is at index 0 is it not?
62 raise(Puppet::ParseError, 'values_at(): Stop index in ' +
63 'given indices range exceeds array size')
67 when /^(\.\.|\-)$/ then (start .. stop)
68 when /^(\.\.\.)$/ then (start ... stop) # Exclusive of last element ...
71 range.each { |i| indices_list << i.to_i }
73 # Only positive numbers allowed in this case ...
74 if not i.match(/^\d+$/)
75 raise(Puppet::ParseError, 'values_at(): Unknown format ' +
79 # In Puppet numbers are often string-encoded ...
82 if i > array.size - 1 # Same story. First element is at index 0 ...
83 raise(Puppet::ParseError, 'values_at(): Given index ' +
91 # We remove nil values as they make no sense in Puppet DSL ...
92 result = indices_list.collect { |i| array[i] }.compact
98 # vim: set ts=2 sw=2 et :