4 module Puppet::Parser::Functions
5 newfunction(:count, :type => :rvalue, :arity => -2, :doc => <<-DOC
6 Takes an array as first argument and an optional second argument.
7 Count the number of elements in array that is equal to the second argument.
8 If called with only an array, it counts the number of elements that are not nil/undef/empty-string.
10 Note: equality is tested with a Ruby method and it is therefore subject to what Ruby considers
11 to be equal. For strings this means that equality is case sensitive.
13 In Puppet core, counting can be done in general by using a combination of the core functions
14 filter() (since Puppet 4.0.0) and length() (since Puppet 5.5.0, before that in stdlib).
15 Example below shows counting values that are not undef.
17 notice([42, "hello", undef].filter |$x| { $x =~ NotUndef }.length)
19 Would notice the value 2.
25 raise(ArgumentError, "count(): Wrong number of arguments given #{args.size} for 1 or 2.")
28 collection, item = args
33 collection.count { |obj| !obj.nil? && obj != :undef && obj != '' }