tags:

views:

35

answers:

1

I am writing data to yaml files from ruby and I frequently get aliases dotted about the file. Things like:

- &id001  
  somekey: somevalue
- *id001

In my case I am using the yaml files to aid readability and add names to values in the files as the existing data is just | separated values with no keys. How can I prevent the yaml files being written with aliases?

[Edit]

For further clarification here is an example of the type of data and problem.

The original data looks like:

Ham|2.00|1
Eggs|0.50|12
Milk|2.00|2

And I have written a ruby script to convert it to yaml, which also looks at an sql file to get the appropriate names. The yaml file looks like:

---
- !omap
  - name: Ham
  - &id001
    price: 2.00
  - quantity: 1
- !omap
  - name: Eggs
  - price: 0.50
  - quantity: 12
- !omap
  - name: Milk
  - *id001
  - quantity: 1

This causes a problem in large data sets because the aliases may be nowhere near each other and it makes it hard to read.

A: 

Why are you using YAML::Omap's?

A much simpler and cleaner solution would be to first read the data into an array of hashes, as such:

a = [ {'name' => 'Ham', 'price' => 2.00, 'quantity' => 1},
      {'name' => 'Eggs', 'price' => 0.50, 'quantity' => 12},
      {'name' => 'Milk', 'price' => 2.00, 'quantity' => 2} ]

and then just do:

a.to_yaml

resulting in:

--- 
- price: 2.0
  name: Ham
  quantity: 1
- price: 0.5
  name: Eggs
  quantity: 12
- price: 2.0
  name: Milk
  quantity: 2

Would that work for you?

Sérgio Gomes
The yaml files at some point get written back to those pipe separated files. In these order is important and I found that when using a normal hash the order of items can get jumbled.
oh_cripes
I take it you're using Ruby 1.8, then? You're right, hashes aren't ordered in Ruby 1.8, so the order of the elements may be changed.Is the order of the elements relevant in the YAML file, or just the pipe separated one? If so, you might consider simply reordering the elements when converting from YAML to the pipe-separated file.
Sérgio Gomes
I could do this but would it solve my problem? Do you think the fact that I'm using Omap's is causing aliases to be added?
oh_cripes