: 
http://rubylearning.com/
http://rubylearning.com/satishtalim/tutorial.html
http://rubylearning.com/download/downloads.html
http://rubylearning.com/other/certification.html
http://rubylearning.com/blog/
http://rubylearning.com/other/ruby_news.html
http://rubylearning.com/other/testimonials.html
http://rubylearning.com/jobs/ruby_jobs.html
http://rubylearning.com/other/ruby_gurus.html
http://rubylearning.com/satishtalim/services.html
http://rubylearning.com/contact/contact.html
http://rubylearning.com/satishtalim/about.html


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



Learning Ruby Navigation                                                         <Mutable / Immutable Objects  | TOC  |  Constants>