1 # TODO(Krzysztof Wilczynski): We need to add support for regular expression ...
2 # TODO(Krzysztof Wilczynski): Support for strings and hashes too ...
6 module Puppet::Parser::Functions
7 newfunction(:member, :type => :rvalue, :doc => <<-DOC
9 This function determines if a variable is a member of an array.
11 The variable can be a string, fixnum, or array.
13 > **Note**: This function does not support nested arrays. If the first argument contains
14 nested arrays, it will not recurse through them.
17 member(['a','b'], 'b') # Returns: true
18 member(['a', 'b', 'c'], ['a', 'b']) # Returns: true
19 member(['a','b'], 'c') # Returns: false
20 member(['a', 'b', 'c'], ['d', 'b']) # Returns: false
23 Since Puppet 4.0.0 the same can be performed in the Puppet language.
24 For single values the operator `in` can be used:
25 `'a' in ['a', 'b'] # true`
26 For arrays by using operator `-` to compute a diff:
27 `['d', 'b'] - ['a', 'b', 'c'] == [] # false because 'd' is not subtracted`
28 `['a', 'b'] - ['a', 'b', 'c'] == [] # true because both 'a' and 'b' are subtracted`
31 Returns whether the given value was a member of the array
33 > **Note** that since Puppet 5.2.0, the general form to test the content of an array or
34 hash is to use the built-in [`any`](https://puppet.com/docs/puppet/latest/function.html#any)
35 and [`all`](https://puppet.com/docs/puppet/latest/function.html#all) functions.
39 raise(Puppet::ParseError, "member(): Wrong number of arguments given (#{arguments.size} for 2)") if arguments.size < 2
43 unless array.is_a?(Array)
44 raise(Puppet::ParseError, 'member(): Requires array to work with')
47 unless arguments[1].is_a?(String) || arguments[1].is_a?(Integer) || arguments[1].is_a?(Array)
48 raise(Puppet::ParseError, 'member(): Item to search for must be a string, fixnum, or array')
51 item = if arguments[1].is_a?(String) || arguments[1].is_a?(Integer)
57 raise(Puppet::ParseError, 'member(): You must provide item to search for within array given') if item.respond_to?('empty?') && item.empty?
59 result = (item - array).empty?
65 # vim: set ts=2 sw=2 et :