Search code examples
rubyoctal

Why is 032 different than 32 in Ruby?


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?


Solution

  • 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"