Skip to content
instance method

Kernel#Integer

(::int | ::_ToI int_like, ?exception: true) -> ::Integer
(::int | ::_ToI int_like, exception: bool) -> ::Integer?
(::string str, ::int base, ?exception: true) -> ::Integer
(::string str, ::int base, exception: bool) -> ::Integer?
(untyped, ?untyped, ?exception: bool) -> ::Integer?
Integer(object, base = 0, exception: true) → integer or nil

Returns an integer converted from object.

Tries to convert object to an integer using to_int first and to_i second; see below for exceptions.

With a non-zero base, object must be a string or convertible to a string.

Numeric objects

With an integer argument object given, returns object:

Example
Integer(1)                # => 1
Integer(-1)               # => -1

With a floating-point argument object given, returns object truncated to an integer:

Example
Integer(1.9)              # => 1  # Rounds toward zero.
Integer(-1.9)             # => -1 # Rounds toward zero.

String objects

With a string argument object and zero base given, returns object converted to an integer in base 10:

Example
Integer('100')    # => 100
Integer('-100')   # => -100

With base zero, string object may contain leading characters to specify the actual base (radix indicator):

Example
Integer('0100')  # => 64  # Leading '0' specifies base 8.
Integer('0b100') # => 4   # Leading '0b' specifies base 2.
Integer('0x100') # => 256 # Leading '0x' specifies base 16.

With a positive base (in range 2..36) given, returns object converted to an integer in the given base:

Example
Integer('100', 2)   # => 4
Integer('100', 8)   # => 64
Integer('-100', 16) # => -256

With a negative base (in range -36..-2) given, returns object converted to the radix indicator if it exists or base:

Example
Integer('0x100', -2)   # => 256
Integer('100', -2)     # => 4
Integer('0b100', -8)   # => 4
Integer('100', -8)     # => 64
Integer('0o100', -10)  # => 64
Integer('100', -10)    # => 100

base -1 is equivalent to the -10 case.

When converting strings, surrounding whitespace and embedded underscores are allowed and ignored:

Example
Integer(' 100 ')      # => 100
Integer('-1_0_0', 16) # => -256

Other classes

Examples with object of various other classes:

Example
Integer(Rational(9, 10)) # => 0  # Rounds toward zero.
Integer(Complex(2, 0))   # => 2  # Imaginary part must be zero.
Integer(Time.now)        # => 1650974042

Keywords

With the optional keyword argument exception given as true (the default):

With exception given as false, an exception of any kind is suppressed and nil is returned.

See also #Hash #iterator? #gsub #j also in 4.1 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0