【问题标题】:How to edit a YAML file using Ruby without changing the comments and the indentation如何使用 Ruby 编辑 YAML 文件而不更改注释和缩进
【发布时间】:2014-09-02 12:39:18
【问题描述】:

我试图编辑一个 YAML 文件键/值,但它没有保留缩进,并且实际文件中存在 cmets。

我该如何解决?

【问题讨论】:

标签: ruby yaml


【解决方案1】:

当您将 YAML 文件解析为对象时,无法保留注释,因为 Ruby 中的对象(数组或哈希)没有内部注释自己的方式。注释只存在于支持注释的源代码或数据文件中,但无论哪种情况,它们都会被解释器忽略:

require 'yaml'
hash = YAML.load(<<EOT)
---
#foo bar
foo: bar
EOT

hash
# => {"foo"=>"bar"}

同样,无法保留 YAML 文件中的缩进,因为对象无法知道文件中的缩进是什么。

【讨论】:

    猜你喜欢
    • 2021-12-11
    • 2015-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-19
    • 2020-12-14
    相关资源
    最近更新 更多