Update stdlib and concat to 6.1.0 both
[mirror/dsa-puppet.git] / 3rdparty / modules / stdlib / lib / puppet / parser / functions / delete_regex.rb
1 #
2 #  delete_regex.rb
3 #  Please note: This function is an implementation of a Ruby class and as such may not be entirely UTF8 compatible. To ensure compatibility please use this function with Ruby 2.4.0 or greater - https://bugs.ruby-lang.org/issues/10085.
4 #
5 module Puppet::Parser::Functions
6   newfunction(:delete_regex, :type => :rvalue, :doc => <<-DOC
7     @summary
8       Deletes all instances of a given element that match a regular expression
9       from an array or key from a hash.
10
11     Multiple regular expressions are assumed to be matched as an OR.
12
13     @example Example usage
14
15       delete_regex(['a','b','c','b'], 'b')
16       Would return: ['a','c']
17
18       delete_regex(['a','b','c','b'], ['b', 'c'])
19       Would return: ['a']
20
21       delete_regex({'a'=>1,'b'=>2,'c'=>3}, 'b')
22       Would return: {'a'=>1,'c'=>3}
23
24       delete_regex({'a'=>1,'b'=>2,'c'=>3}, '^a$')
25       Would return: {'b'=>2,'c'=>3}
26
27     > *Note:*
28     Since Puppet 4 this can be done in general with the built-in
29     [`filter`](https://puppet.com/docs/puppet/latest/function.html#filter) function:
30     ["aaa", "aba", "aca"].filter |$val| { $val !~ /b/ }
31     Would return: ['aaa', 'aca']
32
33     @return [Array] The given array now missing all targeted values.
34   DOC
35              ) do |arguments|
36
37     raise(Puppet::ParseError, "delete_regex(): Wrong number of arguments given #{arguments.size} for 2") unless arguments.size == 2
38
39     collection = arguments[0].dup
40     Array(arguments[1]).each do |item|
41       case collection
42       when Array, Hash, String
43         collection.reject! { |coll_item| (coll_item =~ %r{\b#{item}\b}) }
44       else
45         raise(TypeError, "delete_regex(): First argument must be an Array, Hash, or String. Given an argument of class #{collection.class}.")
46       end
47     end
48     collection
49   end
50 end
51
52 # vim: set ts=2 sw=2 et :