Puppet Function: num2bool

Defined in:
vendor_modules/stdlib/lib/puppet/parser/functions/num2bool.rb
Function type:
Ruby 3.x API

Summary

This function converts a number or a string representation of a number into a true boolean.

Overview

num2bool()Boolean

> Note: that since Puppet 5.0.0 the same can be achieved with the Puppet Type System. See the new() function in Puppet for the many available type conversions.

Returns:

  • (Boolean)

    Boolean(0) # false for any zero or negative number Boolean(1) # true for any positive number



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'vendor_modules/stdlib/lib/puppet/parser/functions/num2bool.rb', line 7

newfunction(:num2bool, type: :rvalue, doc: <<-DOC
  @summary
    This function converts a number or a string representation of a number into a
    true boolean.

  > *Note:* that since Puppet 5.0.0 the same can be achieved with the Puppet Type System.
  See the new() function in Puppet for the many available type conversions.

  @return [Boolean]
      Boolean(0) # false for any zero or negative number
      Boolean(1) # true for any positive number
  DOC
) do |arguments|
  raise(Puppet::ParseError, "num2bool(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size != 1

  number = arguments[0]

  case number
  when Numeric
    # Yay, it's a number
  when String
    begin
      number = Float(number)
    rescue ArgumentError => ex
      raise(Puppet::ParseError, "num2bool(): '#{number}' does not look like a number: #{ex.message}")
    end
  else
    begin
      number = number.to_s
    rescue NoMethodError => ex
      raise(Puppet::ParseError, "num2bool(): Unable to parse argument: #{ex.message}")
    end
  end

  # Truncate Floats
  number = number.to_i

  # Return true for any positive number and false otherwise
  return number > 0
end