What is the proper way to deal with leading zeros in Ruby?
0112.to_s
=> \"74\"
0112.to_i
=> 74
Why is it converting 0112
A numeric literal that starts with 0
is an octal representation, except the literals that start with 0x
which represent hexadecimal numbers or 0b
which represent binary numbers.
1 * 8**2 + 1 * 8**1 + 2 * 8**0 == 74
To convert it to 0112
, use String#% or Kernel#sprintf with an appropriate format string:
'0%o' % 0112 # 0: leading zero, %o: represent as an octal
# => "0112"