问题描述
我想从数字中删除前导零。我想使用 Integer(i)
而不是 i.to_i
来救援 / code>无。
I want to remove leading zeros from a number. I want to use
Integer(i)
instead of i.to_i
in order to rescue
nil.
"011,12,h,013,14".split(",").map{|i| Integer i rescue nil}
我想要得到:
[11,12,nil,13,14]
但是,相反,我得到了:
but, instead I get this:
[9, 12, nil, 11, 14]
可能是什么问题?
推荐答案
来自
Kernel#的:
[…]
如果 arg 是 String
,当 base 被省略或等于零时,基数指示符( 0
, 0b
和 0x
)。
[…]
[…] If arg is a
String
, when base is omitted or equals zero, radix indicators (0
, 0b
, and 0x
) are honored. […]
您省略了 base ,因此前导 0
表示以8为底(或)转换成整数时使用。 的工作方式相同( 011 == 9
得出 true
)。如果不应该使用这些前缀/基数指示符,并且字符串表示的整数应被视为以10为底的整数(或)之一,通过 10
作为 base :
You're omitting base so the leading
0
in your strings means base-8 (or octal) is used by the conversion into integers. Integer literals work the same way (011 == 9
yields true
). If those prefixes/radix indicators shouldn't be honored and the integers represented by the strings should be treated as base-10 (or decimal) one, pass 10
for base:
"011,12,h,013,14".split(",").map{|i| Integer(i, 10) rescue nil} # => [11, 12, nil, 13, 14]
这篇关于如何使用Ruby删除前导零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!