YAML bug: custom key types in a Hash

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.

reddaly@gmail.com wrote:

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

--
       vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407