Ruby 2 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.
  1. # p051gamecharacters.rb  
  2. class GameCharacter  
  3.   def initialize(power, type, weapons)  
  4.     @power = power  
  5.     @type = type  
  6.     @weapons = weapons  
  7.   end  
  8.   attr_reader :power:type:weapons  
  9. 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.
  1. # p052dumpgc.rb  
  2. require_relative 'p051gamecharacters'  
  3. gc = GameCharacter.new(120, 'Magician', ['spells''invisibility'])  
  4. puts "#{gc.power} #{gc.type}"  
  5. gc.weapons.each do |w|  
  6.   puts w  
  7. end  
  8.   
  9. File.open('game''w+'do |f|  
  10.   Marshal.dump(gc, f)  
  11. end  
The program p053loadgc.rb uses Marshal.load to read it in.
  1. # p053loadgc.rb  
  2. require_relative 'p051gamecharacters'  
  3. File.open('game'do |f|  
  4.   @gc = Marshal.load(f)  
  5. end  
  6.   
  7. puts "#{@gc.power} #{@gc.type}"  
  8. @gc.weapons.each do |w|  
  9.   puts w  
  10. 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.