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,
# since we are trying to write to it.
File.open filename, ​'w'​ ​do​ |f|
f.write test_string
end
read_string = File.read filename
puts(read_string == test_string)
true

File.open is how you open a file, of course. It creates the file object, calls it f (because that’s what we said to call it), runs all the code until it gets to the end, and then closes the file. When you open a file, you always have to close it again. In most programming languages you have to remember to do this, but Ruby takes care of it for you at the end. Reading files is even easier than writing them; with File.read Ruby takes care of everything behind the scenes. (I’m not sure why they made writing more complicated, but we’ll fix that in just a bit.)

Well, that’s all well and good if all you want to save and load are single strings. But what if you wanted to save an array of strings? Or an array of integers and floats? And what about all of the other classes of objects that we don’t even cover until the next chapter? What about the bunnies?

All right, one thing at a time. Now we can definitely save any kind of object, just as long as we have some well-defined way of converting from a general object to a string and back again. So, maybe an array would be represented as text separated by commas. But what if you wanted to save a string with commas? Well, maybe you could escape the commas somehow….

Figuring this all out would take us a ridiculous amount of time. I mean, it’s pretty cool that you can do it at all, but you didn’t pay good money for “pretty cool.” No sir, this is a De-Luxe-Supremium book you have here. And for that, my friend, we need some serious saving. We need some full-frontal loading. Yes, when you’re looking for De-Luxe-Supremium, you want YAML.

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

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