YAML self reference issue

S

Steve Tuckner

------=_NextPart_000_04C3_01C3B277.5F46E580
Content-Type: text/plain;
charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

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}"


Steve Tuckner




------=_NextPart_000_04C3_01C3B277.5F46E580--
 
T

T. Onoma

y = YamlTest.load
puts "y = #{y.a.class}"
y.save
y2 = YamlTest.load
puts "y2 = #{y.a.class}"

First of all is the last line supposed to be:

puts "y2 = #{y2.a.class}"

-t0
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,743
Messages
2,569,478
Members
44,899
Latest member
RodneyMcAu

Latest Threads

Top