Update stdlib and concat to 6.1.0 both
[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     @summary
7       **Deprecated:** This function converts an array into a hash.
8
9     @return
10       the converted array as a hash
11     @example Example Usage:
12       hash(['a',1,'b',2,'c',3]) # Returns: {'a'=>1,'b'=>2,'c'=>3}
13
14     > **Note:** This function has been replaced with the built-in ability to create a new value of almost any
15     data type - see the built-in [`Hash.new`](https://puppet.com/docs/puppet/latest/function.html#conversion-to-hash-and-struct) function
16     in Puppet.
17     This example shows the equivalent expression in the Puppet language:
18       ```
19       Hash(['a',1,'b',2,'c',3])
20       Hash([['a',1],['b',2],['c',3]])
21       ```
22     DOC
23              ) do |arguments|
24
25     raise(Puppet::ParseError, "hash(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty?
26
27     array = arguments[0]
28
29     unless array.is_a?(Array)
30       raise(Puppet::ParseError, 'hash(): Requires array to work with')
31     end
32
33     result = {}
34
35     begin
36       # This is to make it compatible with older version of Ruby ...
37       array  = array.flatten
38       result = Hash[*array]
39     rescue StandardError
40       raise(Puppet::ParseError, 'hash(): Unable to compute hash from array given')
41     end
42
43     return result
44   end
45 end
46
47 # vim: set ts=2 sw=2 et :