我有一些具有互锁结构的大哈希(>10⁵ 键)。它们作为 YAML 存储在磁盘上。我想通过在 YAML 中使用 anchor 和引用来避免重复,但我无法弄清楚是否有办法在哈希中隐式地执行此操作,例如 #to_yaml
方法将正确标记 anchor 节点。
所需的 YAML:
---
parent1:
common-element-1: &CE1
complex-structure-goes: here
parent2:
uncomment-element-1:
blah: blah
<<: *CE1
ruby 代码:
hsh = {
'parent1' => {
'common-element-1' => {
'complex-structure-goes' => 'here',
},
'parent2' => {
'uncommon-element-1' => {
'blah' => 'blah',
},
'<<' => '*CE1',
},
}
引用非常简单——但是如何将 &CE1
anchor 嵌入到 Ruby 哈希的 'common-element-1'
项中?
我想尽可能多地使用原生 Ruby 基本类型(如 Hash
),而不是与构建器和发射器等混在一起——我绝对不'不想手动编写 YAML!
我看过Read and write YAML files without destroying anchors and aliases?和 its relative ,以及其他地方,但还没有找到答案——至少我不明白。
谢谢!
最佳答案
如果您使用相同的 Ruby 对象,YAML 库将为您设置引用:
> common = {"ohai" => "I am common"}
> doc = {"parent1" => {"id" => 1, "stuff" => common}, "parent2" => {"id" => 2, "stuff" => common}}
> puts doc.to_yaml
---
parent1:
id: 1
stuff: &70133422893680
ohai: I am common
parent2:
id: 2
stuff: *70133422893680
不过,我不确定是否有直接的方法来定义彼此为子集的哈希。也许需要稍微调整一下您的结构?
关于ruby - 注释 Ruby 结构以在 #to_yaml 上包含 anchor /引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14610918/