2 # join_keys_to_values.rb
4 module Puppet::Parser::Functions
5 newfunction(:join_keys_to_values, :type => :rvalue, :doc => <<-DOC
6 This function joins each key of a hash to that key's corresponding value with a
7 separator. Keys are cast to strings. If values are arrays, multiple keys
8 are added for each element. The return value is an array in
9 which each element is one joined key/value pair.
13 join_keys_to_values({'a'=>1,'b'=>2}, " is ")
15 Would result in: ["a is 1","b is 2"]
17 join_keys_to_values({'a'=>1,'b'=>[2,3]}, " is ")
19 Would result in: ["a is 1","b is 2","b is 3"]
21 Note: Since Puppet 5.0.0 - for more detailed control over the formatting (including indentations and
22 line breaks, delimiters around arrays and hash entries, between key/values in hash entries, and individual
23 formatting of values in the array) - see the `new` function for `String` and its formatting
24 options for `Array` and `Hash`.
28 # Validate the number of arguments.
29 if arguments.size != 2
30 raise(Puppet::ParseError, "join_keys_to_values(): Takes exactly two arguments, but #{arguments.size} given.")
33 # Validate the first argument.
35 unless hash.is_a?(Hash)
36 raise(TypeError, "join_keys_to_values(): The first argument must be a hash, but a #{hash.class} was given.")
39 # Validate the second argument.
40 separator = arguments[1]
41 unless separator.is_a?(String)
42 raise(TypeError, "join_keys_to_values(): The second argument must be a string, but a #{separator.class} was given.")
45 # Join the keys to their values.
48 v.map { |va| String(k) + separator + String(va) }
49 elsif String(v) == 'undef'
52 String(k) + separator + String(v)
58 # vim: set ts=2 sw=2 et :