Java features the ability to serialize objects, letting you store them somewhere and reconstitute them when needed. Ruby calls this kind of serialization marshaling.
We will write a basic class p051gamecharacters.rb just for testing marshalling.
- # p051gamecharacters.rb
- class GameCharacter
- def initialize(power, type, weapons)
- @power = power
- @type = type
- @weapons = weapons
- end
- attr_reader :power, :type, :weapons
- end
The program p052dumpgc.rb creates an object of the above class and then uses Marshal.dump to save a serialized version of it to the disk.
- # p052dumpgc.rb
- require_relative 'p051gamecharacters'
- gc = GameCharacter.new(120, 'Magician', ['spells', 'invisibility'])
- puts "#{gc.power} #{gc.type}"
- gc.weapons.each do |w|
- puts w
- end
- File.open('game', 'w+') do |f|
- Marshal.dump(gc, f)
- end
The program p053loadgc.rb uses Marshal.load to read it in.
- # p053loadgc.rb
- require_relative 'p051gamecharacters'
- File.open('game') do |f|
- @gc = Marshal.load(f)
- end
- puts "#{@gc.power} #{@gc.type}"
- @gc.weapons.each do |w|
- puts w
- end
Marshal only serializes data structures. It can't serialize Ruby code (like Proc objects), or resources allocated by other processes (like file handles or database connections). Marshal just gives you an error when you try to serialize a file.