1. Technology
You can opt-out at any time. Please refer to our privacy policy for contact information.

Serialization in Ruby: Marshal


1 of 3

The Basics

Serializing an object is to convert an object to a byte stream and either store that object for future loading, or sending to another program to be loaded there. There are several common ways to serialize objects in Ruby. The Marshal module is used less often than the other methods, but it's included in the standard library.

At the most basic level, marshaling an object can be as simple as saving an object to a file, and loading that object again the next time a script is run. This can be particularly useful, as it's easy to save your program's state between executions.

First, saving (referred to as "dumping") an object. This is achieved by calling the Marshal::dump method. It takes a single argument, the object to be dumped. It returns a string, the serialized form of this object. Note that this string is not human-readable, it will contain non-ASCII characters. More on this aspect of Marshal later in the article.

Optionally, a second argument can be passed to Marshal::dump, an IO object (such as a file open for writing) for the object to be written to. If the serialized object is written to an IO object, it won't be returned as a string.

Next, loading an object. This is rather straightforward, Marshal::load takes an IO object as an argument and will load an object from the IO stream and return it. Optionally, if there are more than one marshaled objects in the IO object, you can pass a block to Marshal::load, which will be called for every marshaled object it finds in the IO.

The following code is a very simple example of how to use Marshal. At the beginning of the program, if a file called counter exists in the current directory, it will open it and load an object from it. This object will be a number, which will be incremented and then stored back in the file. This is a clone of a common "Hello World" PHP script, to implement a counter for a web page.

#!/usr/bin/env ruby

counter = if File.exists?('counter')
           File.open('counter') do|file|

puts "Counter is currently at #{counter}"
puts "incrementing to #{counter + 1}"

counter += 1

File.open('counter','w') do|file|
 Marshal.dump(counter, file)
  1. About.com
  2. Technology
  3. Ruby
  4. Advanced Ruby
  5. Serialization
  6. Serialization in Ruby: Marshal

©2014 About.com. All rights reserved.