Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to work with leading zeros in integers

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
like image 836
Joel Avatar asked Feb 16 '15 16:02

Joel


1 Answers

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"
like image 182
falsetru Avatar answered Sep 29 '22 08:09

falsetru