Ruby Marshal
Marshal.dump packs an object into a string, and Marshal.load restores it. The restored copy carries the same values but is a separate object.
A custom object round-trip
The Book class stores a title behind a reader. The copy restored from the packed string answers the same title.
class Book
attr_reader :title
def initialize(title)
@title = title
end
end
book = Book.new("Emma")
copy = Marshal.load(Marshal.dump(book))
puts copy.titleA mixed array round-trip
The array mixes a number, a string, a symbol and a nested array. The restored array prints the same values and compares as equal.
values = [1, "two", :three, [4, 5]]
restored = Marshal.load(Marshal.dump(values))
p restored
puts values == restoredThe copy is a different object
The copy and the original hold the same title, so the title comparison is true. equal? checks identity, so it gives false.
class Book
attr_reader :title
def initialize(title)
@title = title
end
end
book = Book.new("Emma")
copy = Marshal.load(Marshal.dump(book))
puts copy.title == book.title
puts copy.equal?(book)Nested values are copied too
The Basket object holds an array of items. Adding an item to the copy leaves the array inside the original basket untouched.
class Basket
attr_reader :items
def initialize(items)
@items = items
end
end
basket = Basket.new(["pen", "book"])
copy = Marshal.load(Marshal.dump(basket))
copy.items << "ruler"
p copy.items
p basket.itemsExample
class Label
attr_reader :name
def initialize(name)
@name = name
end
end
labels = [Label.new("first"), Label.new("second")]
restored = Marshal.load(Marshal.dump(labels))
puts restored[1].name
puts restored[0].equal?(labels[0])Key points
- Marshal.dump turns an object into a packed string.
- Marshal.load turns that string back into an object.
- A restored custom object answers its readers as before.
- The restored object is a separate object from the original.
- equal? compares identity, so a restored copy gives false.
- Nested values inside a container are packed and restored too.
In this example, an array holds two Label objects, and the whole array is packed and restored in one step. The restored second label still answers its name reader. The equal? check shows the restored label is a separate object from the original.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
An object is packed with Marshal.dump and restored with Marshal.load. What does copy.equal?(original) give?