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

Saving and Loading for Grown-Ups

Now that you’re good and afraid, let’s get to it. A file is basically just a sequence of bytes. A string is also, ultimately, just a sequence of bytes. This makes saving strings to files pretty easy, at least conceptually. (And Ruby makes it pretty easy in practice.)

Here’s a quick example where we save a simple string to a file and then read it back out again. (I’ll just show you the program first, and then I’ll talk some more about it.)

# The filename doesn't have to end
# with ".txt", but since it is valid
# text, why not?
filename = ​'ListerQuote.txt'
test_string = ​'I promise that I swear absolutely that '​ +
'I will never mention gazpacho soup again.'
# The 'w' here is for write-access to the file, ...
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