rubynumber-literal

Numeric literals prepended with `0`


Using insert, I push values to an Array as:

myarray=[22,33,44]
myarray.insert(0,02)
# => [2,22,33,44]

If do the following, I get:

myarray.insert(0,020)
# => [16,2,22,33,44]

020 becomes 16? If I do the following, I get:

myarray.insert(0,0200)
# => [128,16,2,22,33,44]

0200 becomes 128? May I know the reason for this?


Solution

  • If the number has a zero in front of it, ruby treats it as an octal number (base 8)

    You can do similar with binary/hexadecimal too

    0x20 => 32 (hexadecimal)
    020 => 16 (octal)
    0b10 => 2 (binary)
    080 => Invalid octal digit