Numeric literals prepended with `0`

不想你离开。 提交于 2019-12-02 03:51:33

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/13947817/numeric-literals-prepended-with-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!