How to work with leading zeros in integers
What is the right way to deal with leading zeros in Ruby?
0112.to_s => "74" 0112.to_i => 74 Why is this converting 0112 to 74 ?
How to convert 0112 to the string "0112" ?
I want to define a method that takes an integer as an argument and returns it with its digits in descending order.
But this does not work for me when I have leading zeros:
def descending_order(n) n.to_s.reverse.to_i end A numeric literal starting with 0 is an octal representation, with the exception of literals starting 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 the appropriate format string:
'0%o' % 0112 # 0: leading zero, %o: represent as an octal # => "0112" You cannot, because the Ruby Integer class does not store leading zeros.
The leading 0 in the numeric literal is interpreted as the prefix:
0and0o: octal number0x: hexadecimal number0b: binary number0d: decimal
It allows you to enter numbers in these databases. The Ruby parser converts literals to their corresponding Integer instances. The prefix or leading zeros are discarded.
Another example is %w for inputting arrays:
ary = %w(foo bar baz) #=> ["foo", "bar", "baz"] Unable to get this %w from ary . The parser turns the literal into an array instance, so the script never sees the literal.
0112 (or 0o112 ) is interpreted (by the parser) as the octal number 112 and turns into an integer 74 .
Decimal 0112 is just 112 , no matter how many zeros you set in front of you:
0d0112 #=> 112 0d00112 #=> 112 0d000112 #=> 112 It looks like extra trailing zeros for floats:
1.0 #=> 1.0 1.00 #=> 1.0 1.000 #=> 1.0 You will probably have to use a string, i.e. "0112"
Another option is to explicitly specify the minimum width, for example:
def descending_order(number, width = 0) sprintf('%0*d', width, number).reverse.to_i end descending_order(123, 4) #=> 3210 descending_order(123, 10) #=> 3210000000