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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The
to_imethod returns the number that is formed by all parseable digits at the start of a string. Your first string starts with a with digit soto_ireturns that, the second string doesn’t start with a digit so 0 is returned. BTW, whitespace is ignored, so" 123abc".to_ireturns 123.