I got the following output in the ruby console.
Integer('009') # => ArgumentError: invalid value for Integer(): "009"
But if I try the convert the same string into Float, it works.
Float('009') # => 9.0
Why does Float convert this while Integer does not?
Kernel#Integer interprets arguments starting with a leading 0 as octal. Because the octal number system ony uses digits 0-7, a number containing a 9 is not defined. From the documentation:
If arg is a String, when base is omitted or equals zero, radix indicators (0, 0b, and 0x) are honored.
Kernel#Float, on the other hand, does not behave this way.
To convert "009" to an integer in base 10 using Integer, you need to pass an optional argument specifying the base:
Integer("009", 10)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With