Ruby YAML 写没有别名 [英] Ruby YAML write without aliases

查看:35
本文介绍了Ruby YAML 写没有别名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将数据从 ruby​​ 写入 yaml 文件,并且我经常在文件中添加别名.诸如此类:

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

- &id001  
  somekey: somevalue
- *id001

在我的例子中,我使用 yaml 文件来帮助可读性并为文件中的值添加名称,因为现有数据只是 | 分隔值,没有键.如何防止使用别名写入 yaml 文件?

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?

为了进一步说明,这里是数据类型和问题的示例.

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

原始数据如下:

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

并且我编写了一个 ruby​​ 脚本将其转换为 yaml,它还查看 sql 文件以获取适当的名称.yaml 文件如下所示:

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.

推荐答案

你为什么使用 YAML::Omap 的?

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} ]

然后就做:

a.to_yaml

导致:

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

这对你有用吗?

这篇关于Ruby YAML 写没有别名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆