Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does `Integer('009')` not work, but `Float('009')` does?

Tags:

ruby

literals

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?

like image 225
patrickS Avatar asked Dec 04 '25 17:12

patrickS


1 Answers

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)
like image 105
Drenmi Avatar answered Dec 06 '25 07:12

Drenmi