# Object.to\_yaml works but .to\_yaml fails

**URL:** <https://www.ruby-forum.com/t/object-to-yaml-works-but-to-yaml-fails/179116>\
**Category:** Ruby\
**Created:** [November 18, 2009, 12:17am UTC](https://www.ruby-forum.com/t/object-to-yaml-works-but-to-yaml-fails/179116 "2009-11-18T00:17:57Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Farrel\_L](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/f/9d8465/32.png) [@Farrel\_L](https://www.ruby-forum.com/u/Farrel_L)\
**Post date:** [November 18, 2009, 12:17am UTC](https://www.ruby-forum.com/t/object-to-yaml-works-but-to-yaml-fails/179116/1 "2009-11-18T00:17:57Z")

</div>

I’ve implemented a custom to\_yaml method for an object. When I call  
to\_yaml on the object everything works as expected.

## rb(main):008:0\> puts area.to\_yaml

Area Description: Deltana, Tanana Flats  
Polygons: []  
Geocodes:  
UGC: AKZ223  
FIPS6: 002290  
Circles: []

Ceiling:  
Altitude:  
=\> nil

However when I put the object in an array I get the following error

irb(main):009:0\> puts [area].to\_yaml  
TypeError: wrong argument type String (expected Data)  
from /usr/lib/ruby/1.8/yaml.rb:391:in `emit' from /usr/lib/ruby/1.8/yaml.rb:391:in`quick\_emit’  
from /usr/lib/ruby/1.8/yaml/rubytypes.rb:107:in `to\_yaml’  
from (irb):9

Here is the implementation of Area#to\_yaml

def to\_yaml( options = {} )  
{  
AREA\_DESC\_YAML =\> self.area\_desc,  
ALTITUDE\_YAML =\> self.altitude,  
CEILING\_YAML =\> self.ceiling,  
CIRCLES\_YAML =\> self.circles,  
GEOCODES\_YAML =\> self.geocodes.inject({}){|h,geocode|  
h.merge( geocode.name =\> geocode.value )},  
POLYGONS\_YAML =\> self.polygons  
}.to\_yaml  
end

AREA\_DESC\_YAML and the others are just strings like “Area Description”  
etc. I’m not enough of a YAML expert to understand why serialization  
fails when the area object is in an array.

Farrel

---

<div class="post-metadata">

**Author:** ![Farrel\_L](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/f/9d8465/32.png) [@Farrel\_L](https://www.ruby-forum.com/u/Farrel_L)\
**Post date:** [November 18, 2009, 12:36am UTC](https://www.ruby-forum.com/t/object-to-yaml-works-but-to-yaml-fails/179116/2 "2009-11-18T00:36:06Z")

</div>

I seemed to have solved this. I had to pass the options hash through  
to the to\_yaml call on the hash created in the to\_yaml method.

Farrel
