strings - ruby substring




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

From the documentation for String#to_i:

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

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?


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




data-conversion