From: 7stud -- Date: 2009-02-28T12:31:59+09:00 Subject: Re: Marshal.load does not create new instances? Ian Trudel wrote: > Marshal does not seem to instantiate given class(es) on load. Moreover, > it will absolutely work as long as the class is define > Seems pretty standard across programming languages. > > This is really annoying considering that I would like to load data onto > one (among many) version of Data class. The version of the class to be > used is determined and set at run-time according to the file loaded; > this is my ultimate goal. > > Any suggestions? > How about something like this: ----------- #a program that dumps an object: class MyData def greet puts "hello" end end d = MyData.new File.open("def1.txt", "w") do |f| Marshal.dump(d, f) end ------------ #program that loads the objects: def1 = <<-def1 class MyData def greet puts "hello" end end def1 def2 = <<-def2 class MyData def greet puts "goodbye" end def shout puts "HEY" end end def2 def3 = <<-def3 class MyData def greet puts "last class" end def cry "Wahhhh wahhh" end end def3 data_classes = { "def1" => def1, "def2" => def2, "def3" => def3 } print "Enter file name: " fname = gets.chomp defname = fname.split(".")[0] eval(data_classes[defname]) begin File.open(fname) do |f| d = Marshal.load(f) d.greet d.shout d.cry end rescue NoMethodError #do nothing ensure f.close unless f.nil? end -- Posted via http://www.ruby-forum.com/.