# YAML bug: custom key types in a Hash

**URL:** <https://www.ruby-forum.com/t/yaml-bug-custom-key-types-in-a-hash/69125>\
**Category:** Ruby\
**Created:** [September 18, 2006, 9:00pm UTC](https://www.ruby-forum.com/t/yaml-bug-custom-key-types-in-a-hash/69125 "2006-09-18T21:00:49Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![reddaly](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/258eb7/32.png) [@reddaly](https://www.ruby-forum.com/u/reddaly)\
**Post date:** [September 18, 2006, 9:00pm UTC](https://www.ruby-forum.com/t/yaml-bug-custom-key-types-in-a-hash/69125/1 "2006-09-18T21:00:49Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![reddaly](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/258eb7/32.png) [@reddaly](https://www.ruby-forum.com/u/reddaly)\
**Post date:** [September 18, 2006, 9:18pm UTC](https://www.ruby-forum.com/t/yaml-bug-custom-key-types-in-a-hash/69125/2 "2006-09-18T21:18:52Z")

</div>

removed\_email\_address@domain.invalid wrote:

> YAML::load({X.new(“bar”) =\> “sailor” }.to\_yaml)  
> 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”}
