2

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?

sawa
  • 165,429
  • 45
  • 277
  • 381

1 Answers1

8

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
steenslag
  • 79,051
  • 16
  • 138
  • 171
Beau Trepp
  • 2,610
  • 4
  • 22
  • 30
  • I didn't know this about Ruby. That sucks! `020` should be `20`. I read further, and apparently this is pretty standard across languages. – Martin Velez Dec 19 '12 at 08:13
  • 3
    I can see why it might be slighty counterintuitive, but the octal syntax makes it easy to use octal numbers. It shouldn't really be an issue either as "020".to_i will give you 20. So the only place you can define it is in your source, and you shouldn't have redundant 0s in front of your numbers anyway :) – Beau Trepp Dec 19 '12 at 08:18
  • I see the benefit. I don't think it is worth the cost. – Martin Velez Dec 19 '12 at 08:21