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 arguments given (#{arguments.size} for 2)") if arguments.size < 2
34 array = arguments.shift
36 unless array.is_a?(Array)
37 raise(Puppet::ParseError, 'values_at(): Requires array to work with')
40 indices = [arguments.shift].flatten() # Get them all ... Pokemon ...
42 if not indices or indices.empty?
43 raise(Puppet::ParseError, 'values_at(): You must provide at least one positive index to collect')
51 if m = i.match(/^(\d+)(\.\.\.?|\-)(\d+)$/)
58 raise(Puppet::ParseError, 'values_at(): Stop index in given indices range is smaller than the start index')
59 elsif stop > array.size - 1 # First element is at index 0 is it not?
60 raise(Puppet::ParseError, 'values_at(): Stop index in given indices range exceeds array size')
64 when /^(\.\.|\-)$/ then (start .. stop)
65 when /^(\.\.\.)$/ then (start ... stop) # Exclusive of last element ...
68 range.each { |i| indices_list << i.to_i }
70 # Only positive numbers allowed in this case ...
71 if not i.match(/^\d+$/)
72 raise(Puppet::ParseError, 'values_at(): Unknown format of given index')
75 # In Puppet numbers are often string-encoded ...
78 if i > array.size - 1 # Same story. First element is at index 0 ...
79 raise(Puppet::ParseError, 'values_at(): Given index exceeds array size')
86 # We remove nil values as they make no sense in Puppet DSL ...
87 result = indices_list.collect { |i| array[i] }.compact
93 # vim: set ts=2 sw=2 et :