Why is 032 different than 32 in Ruby?

前端 未结 4 620
一生所求
一生所求 2021-01-07 10:17

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?

4条回答
  •  不要未来只要你来
    2021-01-07 10:40

    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"
    

提交回复
热议问题