Conversions

To get the string version of an object, we simply write .to_s after it:

var1 = 2
var2 = ​'5'
puts var1.to_s + var2
25

Similarly, .to_i gives the integer version of an object, and .to_f gives the float version. Let’s look at what these three methods do (and don’t do) a little more closely:

var1 = 2
var2 = ​'5'
puts var1.to_s + var2
puts var1 + var2.to_i
25
7

Notice that, even after we got the string version of var1 by calling to_s, var1 was always pointing at 2 and never at '2'. Unless we explicitly reassign var1 (which requires an = sign), it will point at 2 for the life of the program.

Now let’s try some more interesting (and a few just weird) conversions:

Line 1 puts ​'15'​.to_f
2 puts ​'99.999'​.to_f
3 puts ​'99.999'​.to_i
4 puts ​''
5 puts ​'5 is my favorite number!'​.to_i
6 puts ​'Who asked you about 5 or whatever?'​.to_i
7 puts ​'Your momma did.'​.to_f
8 puts ​''
9 puts ​'stringy'​.to_s
10 puts 3.to_i
15.0
99.999
99
5
0
0.0
stringy
3

So, this probably gave you some surprises. The first one is pretty standard, giving 15.0. After that, we converted the string '99.999' to a float and to an integer. The float did what we expected; the integer was, as always, rounded down.

Next, we had some examples of some…unusual strings being converted into numbers. On line 5, to_i ignores the first thing it doesn’t understand (and the rest of the string from that point on). So, the first one was converted to 5, but the others, since they started with letters, were ignored completely, so the computer just picks zero.

Finally, we saw that our last two conversions did nothing at all, just as we would expect.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.224.57.43