March 2009
Intermediate to advanced
194 pages
4h
English
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 ... |