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

hsinxh picture hsinxh · Jan 7, 2012 · Viewed 17.3k times · Source

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?

Answer

DarkDust picture DarkDust · Jan 7, 2012

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.