X-Git-Url: https://git.adam-barratt.org.uk/?a=blobdiff_plain;f=3rdparty%2Fmodules%2Fstdlib%2Flib%2Fpuppet%2Fparser%2Ffunctions%2Fcount.rb;h=71999a8cf891ad871d5181b587e820e65c0db5b6;hb=131e09855e065be940e104d9ab0f18940cc76257;hp=cef263735640f8cfd47f568516f5605637c5385b;hpb=6963202b4b62c2816655ac9532521b018fdf83bd;p=mirror%2Fdsa-puppet.git diff --git a/3rdparty/modules/stdlib/lib/puppet/parser/functions/count.rb b/3rdparty/modules/stdlib/lib/puppet/parser/functions/count.rb index cef263735..71999a8cf 100644 --- a/3rdparty/modules/stdlib/lib/puppet/parser/functions/count.rb +++ b/3rdparty/modules/stdlib/lib/puppet/parser/functions/count.rb @@ -1,21 +1,36 @@ +# +# count.rb +# module Puppet::Parser::Functions - newfunction(:count, :type => :rvalue, :arity => -2, :doc => <<-EOS -Takes an array as first argument and an optional second argument. -Count the number of elements in array that matches second argument. -If called with only an array it counts the number of elements that are not nil/undef. - EOS - ) do |args| - - if (args.size > 2) then + newfunction(:count, :type => :rvalue, :arity => -2, :doc => <<-DOC + Takes an array as first argument and an optional second argument. + Count the number of elements in array that is equal to the second argument. + If called with only an array, it counts the number of elements that are not nil/undef/empty-string. + + Note: equality is tested with a Ruby method and it is therefore subject to what Ruby considers + to be equal. For strings this means that equality is case sensitive. + + In Puppet core, counting can be done in general by using a combination of the core functions + filter() (since Puppet 4.0.0) and length() (since Puppet 5.5.0, before that in stdlib). + Example below shows counting values that are not undef. + + notice([42, "hello", undef].filter |$x| { $x =~ NotUndef }.length) + + Would notice the value 2. + + DOC + ) do |args| + + if args.size > 2 raise(ArgumentError, "count(): Wrong number of arguments given #{args.size} for 1 or 2.") end collection, item = args - if item then + if item collection.count item else - collection.count { |obj| obj != nil && obj != :undef && obj != '' } + collection.count { |obj| !obj.nil? && obj != :undef && obj != '' } end end end