Kernel#Integer
Integer(object, base = 0, exception: true) Kernel#Integer converts an object to an Integer and is the strict sibling of String#to_i. Where to_i quietly returns 0 on garbage input, Integer() raises. That single difference is the reason to reach for it.
Integer("42") # => 42
Integer("42abc") # => raises ArgumentError: invalid value for Integer(): "42abc"
"42abc".to_i # => 42
Signature
Integer is a private method defined on Kernel, so you call it as a bare function — no receiver, no Kernel. prefix, no class to instantiate. It works the same at the top level of a script as it does inside a class body or a module method, and the return value is always a real Integer (never a string, never nil on the success path):
Integer(object, base = 0, exception: true)
object— the value to convert.Integertriesto_intfirst, then falls back toto_i.base— an explicit radix for string inputs, or0to auto-detect from a prefix (0b,0o,0d,0x, or a bare leading0).exception:— whenfalse, returnnilinstead of raising. Added in Ruby 2.6.
Converting numbers
Integers pass through unchanged. Floats truncate toward zero — they don’t round.
Integer(42) # => 42
Integer(1.7) # => 1
Integer(-1.9) # => -1
Integer(Rational(7, 2)) # => 3
A few edge cases worth knowing. Integer(Float::NAN) returns 0 because Float::NAN.to_i is 0. Integer(Float::INFINITY) raises FloatDomainError on modern Ruby. And float precision can bite you on truncation: Integer(0.99999999999999999) is 1 because the literal is already 1.0 at that precision. Don’t use Integer() on floats for financial work; use BigDecimal and convert deliberately.
Converting strings
Integer() is permissive about format and strict about content. Surrounding whitespace and embedded underscores are allowed, but anything that isn’t a clean integer raises:
Integer(" 42 ") # => 42
Integer("1_000_000") # => 1000000
Integer("hello") # => raises ArgumentError
Integer("1e3") # => raises ArgumentError (no scientific notation)
With base: 0 (the default), the string can carry a radix prefix that tells Integer which base to use. The recognized prefixes are 0b for binary, 0o for octal, 0d for decimal (rarely needed, since decimal is the default), and 0x for hex. The block below exercises each of them so you can see the exact return value:
Integer("0b1010") # => 10
Integer("0o17") # => 15
Integer("0x1f") # => 31
Integer("0d42") # => 42
Integer("0100") # => 64 (leading 0 = octal, the classic gotcha)
That last line is the trap. Integer("0100") is 64, not 100, because a bare leading 0 means octal. Pass an explicit base when you mean decimal:
Integer("0100", 10) # => 100
Valid explicit bases are 2..36. Negative bases (-2..-36) are also accepted and honor a radix prefix on the string.
Non-raising mode
The exception: false keyword, added in Ruby 2.6, turns both ArgumentError and TypeError into a nil return. It’s the safe-parse shortcut for handling untrusted input where you’d rather get nil than a crash, and it works the same regardless of which exception would otherwise have fired:
Integer("abc", exception: false) # => nil
Integer(nil, exception: false) # => nil
Integer("42", exception: false) # => 42
It’s the cleanest way to parse user or CLI input without wrapping the call in a begin/rescue block. The fallback on the right side of || only fires when Integer returns nil, so a valid number flows straight through and a bogus one quietly falls back to the default:
port = Integer(ARGV[0], exception: false) || 8080
Errors
Two exceptions to know about, and they catch people with single-class rescues:
ArgumentError— the object was string-like but its contents aren’t a valid integer (or the base is outside2..36).TypeError— the object has neitherto_intnorto_i.nil, symbols, booleans, plainObject.new, and arrays all fall here.
rescue ArgumentError alone misses TypeError. Use exception: false if you don’t want to care which one would have fired.
Strict and lenient integer parsing compared
| Input | Integer() | String#to_i |
|---|---|---|
"42" | 42 | 42 |
"42abc" | raises ArgumentError | 42 |
"abc" | raises ArgumentError | 0 |
" 42 " | 42 | 42 |
"1_000" | 1000 | 0 (stops at _) |
"0x1f" | 31 (with base: 0) | 0 (stops at x) |
nil | raises TypeError | n/a |
Reach for Integer() when invalid input is a bug, and to_i when you want a forgiving default that returns 0 on garbage.
See Also
- Integer class — the class the function returns values of
- String#to_i — the lenient parser contrasted above
- Kernel#Float — sibling conversion with the same
exception:keyword