Why does Ruby's String#to_i sometimes return 0 when the string contains a number?

本小妞迷上赌 提交于 2019-11-27 07:36:06

问题


I was just trying out Ruby and I came across String#to_i. Suppose I have this code:

var1 = '6 sldasdhkjas'
var2 = 'aljdfldjlfjldsfjl 6'

Why does puts var1.to_i output 6 when puts var2.to_i gives 0?


回答1:


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.




回答2:


From the documentation for String#to_i:

Returns the result of interpreting leading characters in str as an integer




回答3:


More exhaustive examples of to_i:

irb(main):013:0* "a".to_i
=> 0
irb(main):014:0> "".to_i
=> 0
irb(main):015:0> nil.to_i
=> 0
irb(main):016:0> "2014".to_i
=> 2014
irb(main):017:0> "abc2014".to_i
=> 0
irb(main):018:0> "2014abc".to_i
=> 2014
irb(main):019:0> " 2014abc".to_i
=> 2014


来源:https://stackoverflow.com/questions/8768865/why-does-rubys-stringto-i-sometimes-return-0-when-the-string-contains-a-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!