Update stdlib and concat to 6.1.0 both
[mirror/dsa-puppet.git] / 3rdparty / modules / stdlib / lib / puppet / parser / functions / delete.rb
1 #
2 # delete.rb
3 #
4 module Puppet::Parser::Functions
5   newfunction(:delete, :type => :rvalue, :doc => <<-DOC
6     @summary
7       Deletes all instances of a given element from an array, substring from a
8       string, or key from a hash.
9
10     @example Example usage
11
12       delete(['a','b','c','b'], 'b')
13       Would return: ['a','c']
14
15       delete({'a'=>1,'b'=>2,'c'=>3}, 'b')
16       Would return: {'a'=>1,'c'=>3}
17
18       delete({'a'=>1,'b'=>2,'c'=>3}, ['b','c'])
19       Would return: {'a'=>1}
20
21       delete('abracadabra', 'bra')
22       Would return: 'acada'
23
24       ['a', 'b', 'c', 'b'] - 'b'
25       Would return: ['a', 'c']
26
27       {'a'=>1,'b'=>2,'c'=>3} - ['b','c'])
28       Would return: {'a' => '1'}
29
30       'abracadabra'.regsubst(/bra/, '', 'G')
31       Would return: 'acada'
32
33     > *Note:*
34     From Puppet 4.0.0 the minus (-) operator deletes values from arrays and keys from a hash
35     `{'a'=>1,'b'=>2,'c'=>3} - ['b','c'])`
36     >
37     A global delete from a string can be performed with the
38     [`regsubst`](https://puppet.com/docs/puppet/latest/function.html#regsubst) function:
39     `'abracadabra'.regsubst(/bra/, '', 'G')`
40
41     In general, the built-in [`filter`](https://puppet.com/docs/puppet/latest/function.html#filter)
42     function can filter out entries from arrays and hashes based on keys and/or values.
43
44     @return [String] The filtered String, if one was given.
45     @return [Hash] The filtered Hash, if one was given.
46     @return [Array] The filtered Array, if one was given.
47   DOC
48              ) do |arguments|
49
50     raise(Puppet::ParseError, "delete(): Wrong number of arguments given #{arguments.size} for 2") unless arguments.size == 2
51
52     collection = arguments[0].dup
53     Array(arguments[1]).each do |item|
54       case collection
55       when Array, Hash
56         collection.delete item
57       when String
58         collection.gsub! item, ''
59       else
60         raise(TypeError, "delete(): First argument must be an Array, String, or Hash. Given an argument of class #{collection.class}.")
61       end
62     end
63     collection
64   end
65 end
66
67 # vim: set ts=2 sw=2 et :