Object serialization

suggest change

Serialization turns an object graph in memory into bytes that you can write to a file, put in a cache, or send to another process. Deserialization rebuilds objects from those bytes. Ruby gives you several ways to do it:

The JSON parsing and generating API is covered in JSON with Ruby, YAML in depth in YAML, and reading settings files in Configuration files. This article is about turning your objects into bytes and back: what each format preserves, how to customize it, how to survive class changes, and what is safe.

The examples were run with Ruby 4.0, json 2.18, pstore 0.2.1 and msgpack 1.8.

Marshal basics

Marshal.dump returns a binary String and Marshal.load turns it back into objects. Your classes need no extra code: Marshal records the class name and every instance variable.

require 'set'

class Book
  attr_reader :title, :tags, :published

  def initialize(title, tags, published)
    @title = title
    @tags = tags
    @published = published
  end
end

book = Book.new('Essential Ruby', Set[:ruby, :programming], Time.utc(2026, 10, 17, 9, 30))

bytes = Marshal.dump(book)
p bytes.encoding
p bytes.bytesize
p bytes[0, 2].bytes   # format version 4.8

copy = Marshal.load(bytes)
p copy.class
p copy.title
p copy.tags
p copy.published
p copy.equal?(book)
#<Encoding:BINARY (ASCII-8BIT)>
131
[4, 8]
Book
"Essential Ruby"
Set[:ruby, :programming]
2026-10-17 09:30:00 UTC
false

The first two bytes are the format version (4.8). It hasn't changed since Ruby 1.8, so data dumped by one Ruby version loads in another. Loading never calls initialize. Marshal allocates an empty object and sets its instance variables directly, so any validation in your constructor is skipped.

Shared references and cycles

Marshal keeps the shape of the object graph. If two places point to the same object, the loaded copy points to one object too, and cycles don't cause infinite recursion:

Node = Struct.new(:name, :children, :parent)

root = Node.new('root', [], nil)
child = Node.new('child', [], root)
root.children << child

address = { city: 'Lisbon' }
people = [{ name: 'Ana', address: address }, { name: 'Rui', address: address }]

copy_root, copy_people = Marshal.load(Marshal.dump([root, people]))

p copy_root.children.first.parent.equal?(copy_root)   # cycle preserved
p copy_people[0][:address].equal?(copy_people[1][:address])  # sharing preserved

copy_people[0][:address][:city] = 'Porto'
p copy_people[1][:address]
p address    # the original is untouched
true
true
{city: "Porto"}
{city: "Lisbon"}

That is why Marshal.load(Marshal.dump(obj)) is the classic deep copy idiom (see Copying and cloning). JSON and MessagePack can't do this: a shared hash is written twice and comes back as two separate hashes, and a cycle makes the generator fail.

Files and streams

The output is binary, so use File.binwrite / File.binread (or "wb" / "rb" modes). Both methods also accept an IO. Marshal.load on an IO reads exactly one object, so you can append several objects to one file and read them back one at a time:

scores = { 'ana' => [90, 85], 'rui' => [70] }

File.binwrite('scores.bin', Marshal.dump(scores))
p Marshal.load(File.binread('scores.bin'))

# Several objects in one file: dump to the IO, load until EOF
File.open('events.bin', 'wb') do |f|
  3.times { |i| Marshal.dump({ id: i, at: Time.at(1_700_000_000 + i).utc }, f) }
end

File.open('events.bin', 'rb') do |f|
  loop do
    p Marshal.load(f)
  rescue EOFError
    break
  end
end
{"ana" => [90, 85], "rui" => [70]}
{id: 0, at: 2023-11-14 22:13:20 UTC}
{id: 1, at: 2023-11-14 22:13:21 UTC}
{id: 2, at: 2023-11-14 22:13:22 UTC}

What Marshal can't dump

Objects that wrap code, operating system resources or interpreter state can't be serialized. Neither can objects whose class has no name, objects with singleton methods, or hashes with a default block:

singleton = +'hello'
def singleton.shout = upcase

candidates = {
  'Proc'            => -> { 42 },
  'Method'          => 1.method(:+),
  'IO'              => $stdout,
  'Mutex'           => Mutex.new,
  'Thread'          => Thread.current,
  'Binding'         => binding,
  'anonymous class' => Class.new.new,
  'singleton'       => singleton,
  'default proc'    => Hash.new { |h, k| h[k] = [] },
}

candidates.each do |label, obj|
  Marshal.dump(obj)
  puts "#{label}: ok"
rescue TypeError => e
  puts "#{label.ljust(16)} #{e.class}: #{e.message}"
end

# A Hash with a plain default value is fine
h = Hash.new(0)
h[:a] += 1
copy = Marshal.load(Marshal.dump(h))
p copy[:missing]
Proc             TypeError: no _dump_data is defined for class Proc
Method           TypeError: no _dump_data is defined for class Method
IO               TypeError: can't dump IO
Mutex            TypeError: no _dump_data is defined for class Thread::Mutex
Thread           TypeError: no _dump_data is defined for class Thread
Binding          TypeError: no _dump_data is defined for class Binding
anonymous class  TypeError: can't dump anonymous class #<Class:0x0000021ecd780fa8>
singleton        TypeError: singleton can't be dumped
default proc     TypeError: can't dump hash with default proc
0

One unserializable object anywhere in the graph makes the whole dump fail. A typical case is a service object holding a logger, a database connection or a memoized lambda. The fix is to control what gets written.

Customizing Marshal

marshal_dump and marshal_load

If a class defines marshal_dump, Marshal writes whatever it returns instead of the instance variables. On load it allocates an empty object and calls marshal_load with that value. Use this to skip caches, locks and connections, and to rebuild them on load:

class PriceList
  attr_reader :currency

  def initialize(currency, prices)
    @currency = currency
    @prices = prices
    @lock = Mutex.new            # can't be dumped
    @total = nil                 # derived, cheap to recompute
  end

  def total
    @lock.synchronize { @total ||= @prices.values.sum }
  end

  # Return any dumpable object; here an Array of the essential state
  def marshal_dump
    [@currency, @prices]
  end

  # Called on an allocated, uninitialized object (initialize is NOT run)
  def marshal_load(state)
    @currency, @prices = state
    @lock = Mutex.new
    @total = nil
  end
end

list = PriceList.new('EUR', { 'tea' => 3, 'cake' => 5 })
list.total

copy = Marshal.load(Marshal.dump(list))
p copy.instance_variables
p copy.total
[:@currency, :@prices, :@lock, :@total]
8

The value returned by marshal_dump is itself marshaled, so it can contain other objects, and shared references inside it still work.

_dump and _load

The older pair is _dump(level) (an instance method that must return a String) and self._load(string) (a class method that builds the object). It suits value objects that already have a compact string form:

# _dump / self._load: the object becomes a String you build yourself
class Version
  include Comparable
  attr_reader :parts

  def initialize(str) = @parts = str.split('.').map(&:to_i)
  def to_s = parts.join('.')
  def <=>(other) = parts <=> other.parts

  def _dump(_level) = to_s
  def self._load(str) = new(str)
end

v = Version.new('3.4.1')
data = Marshal.dump(v)
p data
p Marshal.load(data) > Version.new('3.4.0')
"\x04\bIu:\fVersion\n3.4.1\x06:\x06EF"
true

Unlike marshal_load, _load is a class method you write yourself, so it can build the object through new and run the usual constructor checks. If a class defines both pairs, marshal_dump wins. Prefer marshal_dump/marshal_load in new code: they don't force you to encode everything into a String yourself.

When the class changes

The class name is written into the data, and loading looks it up by name. Long-lived Marshal data (caches, session stores, files on disk) therefore breaks in two ways when you change your code. Here a file is written by version 1 of a program:

# Version 1 of the program
class Account
  def initialize(owner) = @owner = owner
end
File.binwrite('account.bin', Marshal.dump(Account.new('ana')))

Version 2 adds a field. Old data loads, but the new field is nil because initialize never runs:

# Version 2: the class gained a field
class Account
  attr_reader :owner, :currency

  def initialize(owner, currency = 'EUR')
    @owner = owner
    @currency = currency
  end
end

old = Marshal.load(File.binread('account.bin'))
p old.owner
p old.currency     # initialize never ran, so the new field is nil
"ana"
nil

Version 3 renames the class, and the old data can't be loaded at all:

# Version 3: the class was renamed
class Customer; end

begin
  Marshal.load(File.binread('account.bin'))
rescue ArgumentError => e
  puts "#{e.class}: #{e.message}"
end
ArgumentError: undefined class/module Account

The same error appears when the class exists but hasn't been loaded yet, for example with lazy autoloading. Load (or reference) the classes before calling Marshal.load.

To make the stored format evolve on purpose, write an explicit version number with marshal_dump and migrate old shapes in marshal_load:

class Account
  VERSION = 2
  attr_reader :owner, :currency

  def initialize(owner, currency = 'EUR')
    @owner = owner
    @currency = currency
  end

  def marshal_dump = { v: VERSION, owner: @owner, currency: @currency }

  def marshal_load(h)
    case h[:v]
    when 1 then @owner, @currency = h[:owner], 'EUR'   # v1 had no currency
    when 2 then @owner, @currency = h[:owner], h[:currency]
    else raise ArgumentError, "unknown Account version #{h[:v].inspect}"
    end
  end
end

# What Marshal.load does with a hash written by version 1
old = Account.allocate
old.marshal_load({ v: 1, owner: 'ana' })
p [old.owner, old.currency]

current = Marshal.load(Marshal.dump(Account.new('rui', 'USD')))
p [current.owner, current.currency]
["ana", "EUR"]
["rui", "USD"]

Renames still break this. For anything stored for longer than a deploy, a plain Hash dumped as JSON or MessagePack is easier to keep compatible than a dump of your classes.

Marshal and security

Never call Marshal.load on data an attacker could have written. Loading can create an object of any class that is loaded in the process and set its instance variables to anything. Known "gadget chains" in common libraries turn that into remote code execution. There is no safe mode. See Application security.

Marshal.load has two options. Neither one makes untrusted input safe:

config = Marshal.load(Marshal.dump({ 'hosts' => ['a', 'b'], 'port' => 5432 }), freeze: true)
p config.frozen?, config['hosts'].frozen?, config['hosts'][0].frozen?

# proc: is called for every deserialized object, innermost first;
# its return value replaces the object
seen = []
result = Marshal.load(Marshal.dump([1, 'two', { three: 3.0 }]), ->(obj) { seen << obj.class; obj })
p seen
p result
true
true
true
[Integer, TrueClass, String, Symbol, Float, Hash, Array]
[1, "two", {three: 3.0}]

freeze: true deep-freezes the result, which is handy for shared read-only data. The proc runs only after each object has been built, so it can't stop a malicious one from being created. (The TrueClass in the list is the string's encoding flag, which Marshal stores as an extra value.)

If Marshal data must pass through something you don't fully control, such as a cookie, a shared cache or a queue, sign it with an HMAC and refuse anything whose signature doesn't match before loading it:

require 'openssl'

module SignedMarshal
  SECRET = ENV.fetch('MARSHAL_SECRET', 'dev-only-secret-change-me')
  DIGEST = 'SHA256'
  MAC_SIZE = 32

  def self.dump(obj)
    body = Marshal.dump(obj)
    OpenSSL::HMAC.digest(DIGEST, SECRET, body) + body
  end

  def self.load(blob)
    mac = blob.byteslice(0, MAC_SIZE)
    body = blob.byteslice(MAC_SIZE..)
    expected = OpenSSL::HMAC.digest(DIGEST, SECRET, body)
    raise ArgumentError, 'bad signature' unless mac && OpenSSL.secure_compare(mac, expected)

    Marshal.load(body)
  end
end

blob = SignedMarshal.dump({ user_id: 42, role: 'admin' })
p SignedMarshal.load(blob)

tampered = blob.dup
tampered.setbyte(-2, tampered.getbyte(-2) ^ 1)
begin
  SignedMarshal.load(tampered)
rescue ArgumentError => e
  puts e.message
end
{user_id: 42, role: "admin"}
bad signature

OpenSSL.secure_compare takes the same time whether or not the bytes match, so the comparison doesn't leak the expected MAC. A signature proves who wrote the data. It doesn't hide it: anyone can still read signed Marshal data.

PStore: transactional object storage

PStore stores a Hash-like collection of Marshal-able objects in one file. All reads and writes happen inside a transaction. At the end of the block the file is rewritten atomically, and abort throws the changes away. Since Ruby 4.0 pstore is a bundled gem rather than a default one, so add it to your Gemfile when using Bundler.

require 'pstore'

Task = Struct.new(:title, :done)

store = PStore.new('todo.pstore', true)   # true = thread-safe
store.ultra_safe = true                   # extra checks against a corrupted file

store.transaction do
  store[:tasks] ||= []
  store[:tasks] << Task.new('write article', false)
  store[:tasks] << Task.new('run snippets', true)
end

store.transaction do
  store[:tasks].first.done = true
  store.abort                             # discard everything in this block
end

store.transaction(true) do                # read-only
  store[:tasks].each { |t| puts "[#{t.done ? 'x' : ' '}] #{t.title}" }
  p store.roots
end

begin
  store.transaction(true) { store[:tasks] = [] }
rescue PStore::Error => e
  puts "#{e.class}: #{e.message}"
end
[ ] write article
[x] run snippets
[:tasks]
PStore::Error: in read-only transaction

Every transaction reads the whole file, and every write transaction writes the whole file back. That's fine for small tool state and bad for anything large or busy; use SQLite for those. YAML::Store has the same API but writes YAML (see YAML).

Objects as JSON

JSON has no notion of classes, so the usual pattern is explicit: convert an object to a Hash of JSON types on the way out, and build it from a Hash on the way in. Defining to_json(*args) lets the object appear anywhere inside a structure passed to JSON.generate:

require 'json'
require 'time'

Item = Data.define(:sku, :qty)

class Order
  attr_reader :id, :items, :placed_at

  def initialize(id:, items:, placed_at:)
    @id = id
    @items = items
    @placed_at = placed_at
  end

  def to_h
    { id: id, items: items.map(&:to_h), placed_at: placed_at.iso8601 }
  end

  # Lets Order work inside JSON.generate, to_json and nested structures
  def to_json(*args) = to_h.to_json(*args)

  def self.from_h(h)
    new(id: h.fetch(:id),
        items: h.fetch(:items).map { |i| Item.new(**i) },
        placed_at: Time.iso8601(h.fetch(:placed_at)))
  end
end

order = Order.new(id: 7, items: [Item.new(sku: 'A-1', qty: 2)], placed_at: Time.utc(2026, 10, 17, 12))

json = JSON.generate(order)
puts json
puts JSON.pretty_generate({ orders: [order] })

back = Order.from_h(JSON.parse(json, symbolize_names: true))
p back.items
p back.placed_at
{"id":7,"items":[{"sku":"A-1","qty":2}],"placed_at":"2026-10-17T12:00:00Z"}
{
  "orders": [
    {
      "id": 7,
      "items": [
        {
          "sku": "A-1",
          "qty": 2
        }
      ],
      "placed_at": "2026-10-17T12:00:00Z"
    }
  ]
}
[#<data Item sku="A-1", qty=2>]
2026-10-17 12:00:00 UTC

Data and Struct fit this pattern well: to_h gives you a Hash, and Item.new(**hash) (with symbol keys) rebuilds the object and checks that no member is missing. Pass the *args through in to_json: they carry the generator state, so pretty_generate can indent nested objects.

Unknown objects and JSON::Coder

Without a to_json of its own, an object is written as its to_s, which quietly produces useless strings. strict: true turns that into an error. JSON::Coder (json 2.10+) lets you convert unsupported types in one place without adding methods to classes:

require 'json'
require 'bigdecimal'

Point = Struct.new(:x, :y)

# Without help, unknown objects are written using to_s
puts JSON.generate([Point.new(1, 2), Time.utc(2026, 1, 2), :sym])

# strict: true refuses anything that isn't a JSON type
begin
  JSON.generate([Point.new(1, 2)], strict: true)
rescue JSON::GeneratorError => e
  puts "#{e.class}: #{e.message}"
end

# JSON::Coder converts unsupported objects with a block, without monkey patching
coder = JSON::Coder.new do |obj|
  case obj
  when Time       then obj.utc.iso8601(3)
  when Struct     then obj.to_h
  when BigDecimal then obj.to_s('F')
  else raise TypeError, "can't serialize #{obj.class}"
  end
end

puts coder.dump({ at: Time.utc(2026, 1, 2, 3, 4, 5.25r), point: Point.new(1, 2), price: BigDecimal('19.99') })
p coder.load('{"a":[1,2]}')
["#<struct Point x=1, y=2>","2026-01-02 00:00:00 UTC","sym"]
JSON::GeneratorError: Point not allowed in JSON
{"at":"2026-01-02T03:04:05.250Z","point":{"x":1,"y":2},"price":"19.99"}
{"a" => [1, 2]}

JSON additions

The json library can also write a "json_class" key and rebuild the object on parse. json/add/core adds this to Range, Struct, Time, Date, Regexp and other core classes, and your own class can take part by defining to_json and a self.json_create(hash) method:

require 'json'
require 'json/add/core'     # adds to_json/json_create to Range, Struct, Time, Date, ...
require 'json/add/rational'

s = JSON.generate([1..5, Rational(1, 3)])
puts s

p JSON.parse(s)                              # plain hashes
p JSON.parse(s, create_additions: true)      # objects again
p JSON.unsafe_load(s)
[{"json_class":"Range","a":[1,5,false]},{"json_class":"Rational","n":1,"d":3}]
[{"json_class" => "Range", "a" => [1, 5, false]}, {"json_class" => "Rational", "n" => 1, "d" => 3}]
[1..5, (1/3)]
[1..5, (1/3)]

Here the input chooses which class gets instantiated, so this has the same problem as Marshal: only use create_additions: true on data you produced yourself. JSON.parse leaves it off by default. In json 2.18, calling JSON.load with additions enabled implicitly prints a deprecation warning: use JSON.unsafe_load or pass create_additions: true explicitly. The explicit to_h/from_h pattern above is usually the better choice anyway, because the JSON stays readable by other languages.

Objects as YAML

YAML.dump writes any object with a Ruby-specific tag such as !ruby/object:Book, and YAML.load only rebuilds classes you list in permitted_classes:. encode_with / init_with customize the output much like marshal_dump / marshal_load. All of this is covered in YAML. The tags tie the file to your class names just like Marshal does, so for files people edit, convert to a Hash first.

MessagePack

MessagePack has the same data model as JSON plus binary strings and extension types, in a compact binary encoding with libraries for most languages. Install it with gem install msgpack. Hashes and arrays get to_msgpack, and you register your own classes as extension types on a MessagePack::Factory:

require 'msgpack'

data = { 'id' => 7, 'tags' => %w[ruby books], 'ratio' => 0.25, 'blob' => "\x00\xFF".b }
packed = data.to_msgpack
p packed.bytesize
p MessagePack.unpack(packed)

Point = Struct.new(:x, :y)

factory = MessagePack::Factory.new
# Built-in Time extension (type -1, shared with other languages)
factory.register_type(-1, Time,
                      packer: MessagePack::Time::Packer,
                      unpacker: MessagePack::Time::Unpacker)
# Application-specific type 1 for Point
factory.register_type(1, Point,
                      packer: ->(pt) { [pt.x, pt.y].pack('l>l>') },
                      unpacker: ->(s) { Point.new(*s.unpack('l>l>')) })

bytes = factory.dump({ 'at' => Time.utc(2026, 10, 17, 12, 0, 0.5r), 'p' => Point.new(3, -4) })
p bytes.bytesize
loaded = factory.load(bytes)
p loaded["at"].utc, loaded["p"]

begin
  MessagePack.pack(Point.new(1, 2))
rescue NoMethodError => e
  puts "#{e.class}: #{e.message}"
end
46
{"id" => 7, "tags" => ["ruby", "books"], "ratio" => 0.25, "blob" => "\x00\xFF"}
26
2026-10-17 12:00:00.5 UTC
#<struct Point x=3, y=-4>
NoMethodError: undefined method 'to_msgpack' for an instance of Point

Extension types are just a type number plus bytes, so a reader that doesn't know type 1 still gets the raw payload instead of instantiating something. The Time extension (-1) is part of the MessagePack spec, so Go, Python or JavaScript readers understand it. pack/unpack (for bytes) used with l> means big-endian signed 32-bit integers; see Bytes and binary data. When several services share messages and need a schema, use Protocol Buffers instead.

Comparing the formats

The same 1,000 small hashes, dumped and loaded 50 times on one machine:

require 'json'
require 'yaml'
require 'msgpack'

rows = Array.new(1_000) do |i|
  { 'id' => i, 'name' => "user#{i}", 'score' => i * 1.5, 'active' => i.even?, 'tags' => %w[a b] }
end

formats = {
  'Marshal'     => [-> { Marshal.dump(rows) },  ->(s) { Marshal.load(s) }],
  'JSON'        => [-> { JSON.generate(rows) }, ->(s) { JSON.parse(s) }],
  'MessagePack' => [-> { rows.to_msgpack },     ->(s) { MessagePack.unpack(s) }],
  'YAML'        => [-> { YAML.dump(rows) },     ->(s) { YAML.safe_load(s) }],
}

puts 'format       bytes   dump+load x50'
formats.each do |name, (dump, load)|
  bytes = dump.call
  raise "#{name} round trip failed" unless load.call(bytes) == rows
  start = Process.clock_gettime(Process::CLOCK_MONOTONIC)
  50.times { load.call(dump.call) }
  t = Process.clock_gettime(Process::CLOCK_MONOTONIC) - start
  puts format('%-11s %6d   %7.1f ms', name, bytes.bytesize, t * 1000)
end
format       bytes   dump+load x50
Marshal      54911     150.6 ms
JSON         73540      26.5 ms
MessagePack  52509      35.6 ms
YAML         76543    3255.2 ms

Timings vary by machine and data, but the pattern is typical for recent Ruby: the json gem is heavily optimized and fast for plain data, MessagePack is the most compact, Marshal is in between (it stores an encoding flag with every string), and YAML is around 100 times slower. Pick Marshal for what only it can do (arbitrary objects, shared references), not for speed.

Marshal JSON MessagePack YAML
Ships with Ruby yes yes no (gem) yes
Other languages can read it no yes yes yes
Human-readable no yes no yes
Arbitrary Ruby objects yes via to_h / additions via extension types yes (permitted classes)
Shared references, cycles yes no no yes (aliases)
Safe on untrusted input no yes (JSON.parse) yes (without ext types that build objects) yes (safe_load)

Tips

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents