YAML bug: custom key types in a Hash

R

reddaly

I believe this is a YAML bug, or at least a place that needs a more
useful error message. When I define a Hash with a custom key type,
YAML has trouble. The following code should demonstrate the problem:

class X;
def initialize(foo)
@foo = foo;
end;
end;

YAML::load({X.new("bar") => "sailor" }.to_yaml)
# =>
ArgumentError: syntax error on line 2, col -1: ` foo: bar
: sailor

'
from /usr/lib/ruby/1.8/yaml.rb:133:in `load'
from /usr/lib/ruby/1.8/yaml.rb:133:in `load'
from (irb):15
from :0

I'd appreciate any help in getting this to work. If this is truly a
bug, perhaps somebody can tell me how to report it.
 
J

Joel VanderWerf

I believe this is a YAML bug, or at least a place that needs a more
useful error message. When I define a Hash with a custom key type,
YAML has trouble. The following code should demonstrate the problem:

class X;
def initialize(foo)
@foo = foo;
end;
end;

YAML::load({X.new("bar") => "sailor" }.to_yaml)
# =>
ArgumentError: syntax error on line 2, col -1: ` foo: bar
: sailor

'
from /usr/lib/ruby/1.8/yaml.rb:133:in `load'
from /usr/lib/ruby/1.8/yaml.rb:133:in `load'
from (irb):15
from :0

I'd appreciate any help in getting this to work. If this is truly a
bug, perhaps somebody can tell me how to report it.

As a quick workaround, maybe the following will help. It forces yaml to
use a reference instead of the X object itself. A reference seems to be
more easily parsed as a hash key.

require 'yaml'

class X
def initialize(foo)
@foo = foo
end
end

x = X.new("bar")
h = {x => "sailor"}

puts [x,h].to_yaml

ary = YAML::load([x,h].to_yaml)

puts
p ary[1]


and the output is:

---
- &id001 !ruby/object:X
foo: bar
- *id001: sailor

{#<X:0xb7b7be6c @foo="bar">=>"sailor"}
 

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,769
Messages
2,569,582
Members
45,070
Latest member
BiogenixGummies

Latest Threads

Top