I wonder if anyone has an explanation for the behavior of my yamltest.rb
below. When I run it the first time, I get the output:
Creating new file
y = A
y2 = A
And when I run it a second time I get the following output:
y = Hash
y2 = Hash
The problem seems to be that if there is a circular loop in a set of
objects, then it loads the object as a Hash and not as a typed object.
If you comment out the line:
@a.x = @a
Then it works fine both times you run it.
Any ideas why that is?
This is the Prag Programmers distribution
ruby -v
ruby 1.8.0 (2003-08-04) [i386-mswin32]
Steve Tuckner
-------- yamltest.rb -------------------------
require “yaml”
class A
attr_accessor :x
def initialize(x) @x = x
end
end
class YamlTest
class << self
def load
begin
File.open(“test.yaml”) do |f|
YAML::load(f)
end
rescue Errno::ENOENT
puts "Creating new file"
YamlTest.new
end
end
end
attr_reader :a
def initialize @a = A.new(nil) @a.x = @a
end
def save
File.open(“test.yaml”, “w”) {|f| f.write(self.to_yaml)}
end
end
y = YamlTest.load
puts "y = #{y.a.class}"
y.save
y2 = YamlTest.load
puts “y2 = #{y.a.class}”
So it is not necessary to run it twice to see this behavior. New output:
Creating new file
y = a
y2 = Hash
Steve Tuckner
···
-----Original Message-----
From: T. Onoma [mailto:transami@runbox.com]
Sent: Monday, November 24, 2003 11:38 AM
To: ruby-talk ML
Subject: Re: YAML self reference issue
On Monday 24 November 2003 05:40 pm, Steve Tuckner wrote: