Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 756
hsinxh Avatar asked Jan 07 '12 10:01

hsinxh


People also ask

What does string do in Ruby?

String's object holds and manipulates an arbitrary sequence of the bytes that commonly represents a sequence of characters. Creating Strings: To create the string, just put the sequence of characters either in double quotes or single quotes. Also, the user can store the string into some variable.

What is string in Ruby on Rails?

A string is a sequence of one or more characters that may consist of letters, numbers, or symbols. Strings in Ruby are objects, and unlike other languages, strings are mutable, which means they can be changed in place instead of creating new strings. You'll use strings in almost every program you write.

How do you give a string in Ruby?

A string in Ruby is an object (like most things in Ruby). You can create a string with either String::new or as literal (i.e. with the double quotes "" ). But you can also create string with the special %() syntax With the percent sign syntax, the delimiters can be any special character.

How are strings stored in Ruby?

Strings are stored in Ruby using the String object. In addition to providing storage for strings, this object also contains a number of methods which can be used to manipulate strings. As far as creating string objects goes that is as easy as it gets!


1 Answers

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.

like image 124
DarkDust Avatar answered Sep 18 '22 14:09

DarkDust