G
Greg McIntyre
Can somebody tell me why the following code snippet fails?
---8<---8<---8<---8<---8<---
class Parent
def initialize
@x = 5
@child = Child.new(self)
end
end
class Child
def initialize(parent)
@parent = parent # <-- try commenting out this line
end
end
require 'pp'
require 'yaml'
parent = Parent.new
parent_yaml = parent.to_yaml
puts parent_yaml
# --- &id001 !ruby/objectarent
# child: !ruby/object:Child
# parent: *id001
# x: 5
parent2 = YAML.load(parent_yaml)
pp parent2
fail if parent.class != parent2.class
---8<---8<---8<---8<---8<---
It seems YAML works fine for serialising the Parent object _unless_ the
child references it, in which case it looks like the &id001 at the root
of the YAML document throws off the attempt to read it back in as a
Parent and for some reason it resorts to reading it in as a Hash.
What am I doing wrong?
---8<---8<---8<---8<---8<---
class Parent
def initialize
@x = 5
@child = Child.new(self)
end
end
class Child
def initialize(parent)
@parent = parent # <-- try commenting out this line
end
end
require 'pp'
require 'yaml'
parent = Parent.new
parent_yaml = parent.to_yaml
puts parent_yaml
# --- &id001 !ruby/objectarent
# child: !ruby/object:Child
# parent: *id001
# x: 5
parent2 = YAML.load(parent_yaml)
pp parent2
fail if parent.class != parent2.class
---8<---8<---8<---8<---8<---
It seems YAML works fine for serialising the Parent object _unless_ the
child references it, in which case it looks like the &id001 at the root
of the YAML document throws off the attempt to read it back in as a
Parent and for some reason it resorts to reading it in as a Hash.
What am I doing wrong?