Why does Ruby's String#to_i sometimes return 0 when the string contains a number?
17,569
Solution 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.
Solution 2
From the documentation for String#to_i
:
Returns the result of interpreting leading characters in str as an integer
Solution 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
Related videos on Youtube
Comments
-
hsinxh almost 2 years
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
output6
whenputs var2.to_i
gives0
? -
hsinxh over 12 yearsSo that means if there is non-integer character in the beginning of the string, to_i will ignore the rest of the string ?
-
DarkDust over 12 yearsExactly, if the string starts with a non-integer character it immediately stops parsing and returns 0, ignoring any numbers that might come later in the string.
-
Marc Talbot over 12 yearsThat isn't completely true - it will parse through whitespace characters. " 123".to_i will evaluate to 123, as would a string beginning with a tab.