Serializing? Cerealizing? What?
At some point, you will want your Ruby programs to talk to other programs. Usually, if your program is talking to another program, communication between them is done through an Application Programming Interface or API. Don't let that article scare you. An API is just a generic term for any interface which allows one program to either read data from another program or write data to another program. Or both!
One of the simplest interfaces two Ruby programs can share is a file. The first program will transform some of its objects into a string and then write those strings to a file. The second program will look for the file in a shared location (this is particularly easy if both programs are running on the same computer), read it, and turn the strings in the file back into Ruby objects. Take a look back at the Ruby Primer's I/O chapter if you need a refresher on Ruby's file libraries.
This basic concept (transferring data between programs) is essentially what we're referring to when we say "serializing". By turning our Ruby objects into strings we have made them serial: the objects are all lumped together as a string of chracters, one character after another. We've actually covered one method of serialization already:
Object#to_s. In the exercise below, try to write a
to_s method that produces a string
While that strategy does work, it's quite cumbersome. The
from_s method is big, ugly, and fragile. Try sending it some invalid values! It won't be very happy. It's also not very generic; we would have to write a custom
from_s method for every new class. Ugh! Let's not even think about that. Instead, let's move on to Ruby's built-in solution to this problem.