如何使用Ruby删除前导零 [英] How to remove leading zeros using Ruby

查看:84
本文介绍了如何使用Ruby删除前导零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从数字中删除前导零。我想使用 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#的文档#整数


Integer(arg,base = 0)→整数

[…]
如果 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删除前导零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆