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
?
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.
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.
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.
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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With