Skip to Main Content
Learn to Program, 2nd Edition
book

Learn to Program, 2nd Edition

by Chris Pine
March 2009
Intermediate to advanced content levelIntermediate to advanced
194 pages
4h
English
Pragmatic Bookshelf
Content preview from Learn to Program, 2nd Edition

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 ​ ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learn to Program, 3rd Edition

Learn to Program, 3rd Edition

Chris Pine
The Book of Ruby

The Book of Ruby

Huw Collingbourne

Publisher Resources

ISBN: 9781680500172Errata