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 into 74?
How can convert 0112 to a string "0112" ?
I want to define a method that takes integer as a argument and returns it with its digits in descending order.
But this does not seem to work for me when I have leading zeros:
def descending_order(n)
n.to_s.reverse.to_i
end
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With