Why is 032 different than 32 in Ruby?

前端 未结 4 590
一生所求
一生所求 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:38

    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.

    0 讨论(0)
  • 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"
    
    0 讨论(0)
  • 2021-01-07 10:52

    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
    
    0 讨论(0)
  • 2021-01-07 10:54

    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

    0 讨论(0)
提交回复
热议问题