Update puppetlabs/stdlib module
[mirror/dsa-puppet.git] / 3rdparty / modules / stdlib / lib / puppet / parser / functions / hash.rb
1 #
2 # hash.rb
3 #
4 module Puppet::Parser::Functions
5   newfunction(:hash, :type => :rvalue, :doc => <<-DOC
6     This function converts an array into a hash.
7
8     *Examples:*
9
10         hash(['a',1,'b',2,'c',3])
11
12     Would return: {'a'=>1,'b'=>2,'c'=>3}
13
14     Note: Since Puppet 5.0.0 type conversions can in general be performed by using the Puppet Type System.
15     See the function new() in Puppet for a wide range of available type conversions.
16     This example shows the equivalent expression in the Puppet language:
17
18         Hash(['a',1,'b',2,'c',3])
19         Hash([['a',1],['b',2],['c',3]])
20     DOC
21              ) do |arguments|
22
23     raise(Puppet::ParseError, "hash(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty?
24
25     array = arguments[0]
26
27     unless array.is_a?(Array)
28       raise(Puppet::ParseError, 'hash(): Requires array to work with')
29     end
30
31     result = {}
32
33     begin
34       # This is to make it compatible with older version of Ruby ...
35       array  = array.flatten
36       result = Hash[*array]
37     rescue StandardError
38       raise(Puppet::ParseError, 'hash(): Unable to compute hash from array given')
39     end
40
41     return result
42   end
43 end
44
45 # vim: set ts=2 sw=2 et :