作者:mobiledu2502875063 | 来源:互联网 | 2022-12-28 10:29
What is the proper way to deal with leading zeros in Ruby?
在Ruby中处理前导零的正确方法是什么?
0112.to_s
=> "74"
0112.to_i
=> 74
Why is it converting 0112
into 74
?
为什么将0112转换为74?
How can convert 0112
to a string "0112"
?
如何将0112转换为字符串“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
2 个解决方案
3
You can't, because Ruby's Integer
class does not store leading zeros.
你不能,因为Ruby的Integer类不存储前导零。
A leading 0
in a number literal is interpreted as a prefix:
数字文字中的前导0被解释为前缀:
0
and 0o
: octal number
0和0o:八进制数
0x
: hexadecimal number
0x:十六进制数
0b
: binary number
0b:二进制数
0d
: decimal number
0d:十进制数
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.
它允许您在这些基础中输入数字。 Ruby的解析器将文字转换为适当的Integer实例。前缀或前导零被丢弃。
Another example is %w
for entering arrays:
另一个例子是输入数组的%w:
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.
没有办法从ary获得%w。解析器将文字转换为数组实例,因此脚本永远不会看到文字。
0112
(or 0o112
) is interpreted (by the parser) as the octal number 112 and turned into the integer 74
.
0112(或0o112)被解析器(由解析器)解释为八进制数112并且变为整数74。
A decimal 0112 is just 112
, no matter how many zeros you put in front:
小数0112只有112,无论你放在前面有多少个零:
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"
您可能必须使用字符串,即“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