U
umptious
I'm experimenting with Marshal, but I'm having problems making it work
with data structures that use WeakRefs. Marshal saves without
complaining, but the WeakRefs seem to be junk when I load. Hopefully
the program below explains everything. I'm using Ruby 184-15 on Windows
XP Pro.
Am I missing something?
----------------------------------------------------------------------------------------------------------------------------
#!/usr/bin/env ruby
require "WeakRef"
save = false
class Box
def initialize()
@things = []
end
def add(q)
@things.push q
q.set_owner(self)
end
attr_reader :things
end
class Pen
def initialize(name)
@name = name
@owner = nil
end
def set_owner(owner)
@owner = WeakRef.new(owner)
end
attr_reader
name,
wner)
end
if save
box = Box.new()
[Pen.new("Parker 51"), Pen.new("Densho"), Pen.new("Snorkel")].each{
|q| box.add(q) }
File.open('marsh.txt', "w") do |f|
Marshal.dump(box, f)
end
else
File.open("marsh.txt") do |f|
box = Marshal.load(f)
end
end
p box.things[0].owner # Error occurs here...
#c:/ruby/lib/ruby/1.8/WeakRef.rb:64:in `_id2ref': no implicit
conversion
# from nil to integer (TypeError)
# from C:/RubyCode/Adventure.04/scratch.rb:47:in `p'
# from C:/RubyCode/Adventure.04/scratch.rb:47
with data structures that use WeakRefs. Marshal saves without
complaining, but the WeakRefs seem to be junk when I load. Hopefully
the program below explains everything. I'm using Ruby 184-15 on Windows
XP Pro.
Am I missing something?
----------------------------------------------------------------------------------------------------------------------------
#!/usr/bin/env ruby
require "WeakRef"
save = false
class Box
def initialize()
@things = []
end
def add(q)
@things.push q
q.set_owner(self)
end
attr_reader :things
end
class Pen
def initialize(name)
@name = name
@owner = nil
end
def set_owner(owner)
@owner = WeakRef.new(owner)
end
attr_reader
end
if save
box = Box.new()
[Pen.new("Parker 51"), Pen.new("Densho"), Pen.new("Snorkel")].each{
|q| box.add(q) }
File.open('marsh.txt', "w") do |f|
Marshal.dump(box, f)
end
else
File.open("marsh.txt") do |f|
box = Marshal.load(f)
end
end
p box.things[0].owner # Error occurs here...
#c:/ruby/lib/ruby/1.8/WeakRef.rb:64:in `_id2ref': no implicit
conversion
# from nil to integer (TypeError)
# from C:/RubyCode/Adventure.04/scratch.rb:47:in `p'
# from C:/RubyCode/Adventure.04/scratch.rb:47