为什么当字符串包含数字时,Ruby的String#to_i有时返回0? [英] Why does Ruby's String#to_i sometimes return 0 when the string contains a number?
本文介绍了为什么当字符串包含数字时,Ruby的String#to_i有时返回0?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我刚刚尝试Ruby,遇到了 String#to_i
。假设我有以下代码:
I was just trying out Ruby and I came across String#to_i
. Suppose I have this code:
var1 = '6 sldasdhkjas'
var2 = 'aljdfldjlfjldsfjl 6'
为什么放入var1.to_i
输出 6
当放入var2.to_i
给出 0
时?
推荐答案
to_i
方法返回由所有可解析数字开头的数字。您的第一个字符串以数字开头,因此 to_i
返回该数字,第二个字符串不是以数字开头,因此返回0。顺便说一句,空格会被忽略,因此 123abc .to_i
返回123。
The to_i
method returns the number that is formed by all parseable digits at the start of a string. Your first string starts with a with digit so to_i
returns that, the second string doesn't start with a digit so 0 is returned. BTW, whitespace is ignored, so " 123abc".to_i
returns 123.
这篇关于为什么当字符串包含数字时,Ruby的String#to_i有时返回0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文