Why is 032 different than 32 in Ruby?

偶尔善良 提交于 2019-12-09 01:42:41

问题


I have noticed Ruby behaves differently when working with 032 and 32. I once got syntax errors for having 032 instead of just 32 in my code. Can someone explain this to me? Or is there something really wrong with my code itself?


回答1:


What you're seeing is 032 is an octal representation, and 32 is decimal:

>> 032 #=> 26
>> 32 #=> 32
>> "32".to_i(8) #=> 26
>> "32".to_i(10) #=> 32

And, just for completeness, you might need to deal with hexadecimal:

>> 0x32 #=> 50
>> "32".to_i(16) #=> 50

and binary:

>> 0b100000 #=> 32
>> 32.to_s(2) #=> "100000"



回答2:


When you have a zero in front of your number, Ruby interprets it as an octal(base 8 number).

You syntax error is probably something like this:

ruby-1.9.2-p136 :020 > 08
SyntaxError: (irb):20: Invalid octal digit



回答3:


If you start a number with 0 (zero), ruby treats it as an octal, so you normally don't want the zero. You'll have to be more specific about the syntax error.




回答4:


i don't know about syntax errors, but when you prefix a number with zero it means it's octal (base-8)... so 032 is actually 26 in decimal



来源:https://stackoverflow.com/questions/5616617/why-is-032-different-than-32-in-ruby

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