Object Serialization
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.
| 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.
| require 'p051gamecharacters.rb' gc = GameCharacter.new(120, 'Magician', ['spells', 'invisibility']) puts gc.power.to_s + ' ' + 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.
| require 'p051gamecharacters.rb' File.open('game') do |f| @gc = Marshal.load(f) end puts @gc.power.to_s + ' ' + @gc.type + ' ' @gc.weapons.each do |w| puts w + ' ' end |