【问题标题】:Annotating Ruby structures to include anchors/references on #to_yaml注释 Ruby 结构以在 #to_yaml 上包含锚点/引用
【发布时间】:2013-01-30 18:17:15
【问题描述】:

我有一些带有互锁结构的大哈希(>10⁵ 键)。它们作为 YAML 存储在磁盘上。我想通过在 YAML 中使用锚点和引用来避免重复,但我无法弄清楚是否有办法在散列中隐式执行此操作,以便 #to_yaml 方法正确标记锚节点.

所需的 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',
  },
}

引用非常简单——但是如何将 &amp;CE1 锚嵌入到 Ruby 哈希中的 'common-element-1' 项中?

我想尽可能多地使用原生 Ruby 原始类型(如 Hash),而不是与构建器和发射器等混为一谈——我绝对不想写手动 YAML!

我查看了Read and write YAML files without destroying anchors and aliases?its relative 等其他地方,但还没有找到答案——至少我没有理解。

谢谢!

【问题讨论】:

    标签: ruby hash yaml


    【解决方案1】:

    如果您使用相同的 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
    

    不过,我不确定是否有一种直接的方法来定义作为彼此子集的哈希。或许需要稍微调整一下你的结构?

    【讨论】:

    • 我不知道。这太酷了,我认为这符合我的目的。谢谢!
    猜你喜欢
    • 2020-06-23
    • 1970-01-01
    • 1970-01-01
    • 2018-01-10
    • 1970-01-01
    • 2017-12-08
    • 2014-09-18
    • 1970-01-01
    • 2013-01-25
    相关资源
    最近更新 更多