The Ruby String#to_i and Kernel#Integer methods differ in terms of how they convert strings and nil:
to_i() |
Integer() |
|---|---|
| only interprets leading characters as numbers in a string, and ignores characters beyond the end of a valid number. |
throws an ArgumentError if string is not strictly numeric.
|
returns 0 if there's no valid number found at the start of a string.
|
|
does not automatically convert strings with radix indicators (such as 0, 0b, and 0x), instead it requires explicitly passing the integer base (between 2 and 36) to output the integer in a different numeral system (e.g. "100".to_i(2)).
|
automatically converts strings with radix indicators (such as 0, 0b, and 0x), and also accepts base number (between 2 and 36) to be passed in optionally as an argument.
|
returns 0 for nil.
|
throws TypeError for nil.
|
For example:
value |
value.to_i |
Integer(value) |
|---|---|---|
"50" |
50 |
50 |
"50 foo" |
50 |
ArgumentError |
"50 foo 100" |
50 |
ArgumentError |
"50.123" |
50 |
ArgumentError |
"foo bar 50" |
0 |
ArgumentError |
"foo bar" |
0 |
ArgumentError |
"0b100000000" |
0 |
256 |
"0400" |
400 |
256 |
"0x100" |
0 |
256 |
nil |
0 |
TypeError |
For non-string values, Integer method uses to_int first and then to_i for conversion. Therefore, they yield the same result for non-string values.
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.