问题
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
回答1:
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"
回答2:
You can't, because Ruby's Integer
class does not store leading zeros.
A leading 0
in a number literal is interpreted as a prefix:
0
and0o
: octal number0x
: hexadecimal number0b
: binary number0d
: decimal number
It allows you to enter numbers in these bases. Ruby's parser converts the literals to the appropriate Integer
instances. The prefix or leading zeros are discarded.
Another example is %w
for entering arrays:
ary = %w(foo bar baz)
#=> ["foo", "bar", "baz"]
There's no way to get that %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 turned into the integer 74
.
A decimal 0112 is just 112
, no matter how many zeros you put in front:
0d0112 #=> 112
0d00112 #=> 112
0d000112 #=> 112
It's like additional trailing zeros for floats:
1.0 #=> 1.0
1.00 #=> 1.0
1.000 #=> 1.0
You probably have to use a string, i.e. "0112"
Another option is to provide the (minimum) width explicitly, e.g.:
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
来源:https://stackoverflow.com/questions/28545559/how-to-work-with-leading-zeros-in-integers