【问题标题】:ruby yaml don't remove header %YAML 1.1ruby yaml 不删除标头 %YAML 1.1
【发布时间】:2018-09-26 19:04:27
【问题描述】:

我在 ruby​​ 中有一个名为数组的数组,我在 yaml 文件中添加了值,但是在 file.yml 之后,它删除了我的 %YAML 1.1,所以我不会

yaml_string = File.read "file.yaml"
data = YAML.load yaml_string
array.each do |value|
        data["title"] <<"- "+value+"\n"
end
output = YAML.dump data
File.write("file.yaml", output)

在执行之前,标头是存在的,但是在执行之后它会删除它(%YAML 1.1)并且所有行都用#注释,所以我不会

【问题讨论】:

  • 只需使用 YAML。 load_file 函数,它将文件数据读入哈希。请注意,在较新的红宝石中,它位于 Psych 库中 ruby-doc.org/stdlib-2.4.0/libdoc/psych/rdoc/Psych.html
  • 它不起作用 Traceback(最近一次调用最后一次):3:来自 ./test.rb:16:in &lt;main&gt;' 2: from /usr/lib/ruby/2.5.0/psych.rb:497:in load_file' 1:来自 /usr/lib/ruby/2.5.0 /psych.rb:497:in open' /usr/lib/ruby/2.5.0/psych.rb:497:in initialize': 没有这样的文件或目录@rb_sysopen
  • data = YAML.load_file yaml_string
  • 文件是否存在?您可能遇到相对路径错误,即文件不在您的程序正在运行的目录中。
  • 我已经给出了完整路径,上面只是一个例子,而且它告诉我文件太长......

标签: ruby header yaml


【解决方案1】:

我认为这样的事情是你想要做的。

我假设您的 yaml 标题数组与您的数组对象匹配。

否则,如果您只想将 yaml 数组的编号映射到文本,则可以使用 Enum#with_index 之类的东西。

require 'psych'
filename = "sample_yaml.yml"
array = [0, 1, 2, 3]

if File.exists?(filename)
    puts "File exists. :) Parsing the yaml file."
    yaml = Psych.load_file(filename)
    array.each do |value|
        yaml[value]["title"] << " - #{value}" # find the title that matches the index number of array
    end
else
    raise ArgumentError, "bad file name"
end
puts "Outputting to reformatted yaml file"
File.open("reformatted_file.yaml", 'wb') {|f| f.write "%YAML 1.1\n" + Psych.dump(yaml)}

假设像这样的yaml文件

---
- title: zero
- title: one
- title: two
- title: three

输出

---
- title: zero - 0
- title: one - 1
- title: two - 2
- title: three - 3

【讨论】:

  • 不,我的初始包含 %YAML 1.1 --- - 标题:但代码执行后我只有 ---- - 标题:我不想删除 %YAML 1.1
  • 我已经更新了答案以反映这一点。我认为您的想法过于直白,因为该指令是为 yaml 1.2 引入的。 Ruby 在技术上还不支持它。每 @tenderlove github.com/ruby/psych/issues/253#issuecomment-156169539 所以 libyaml 目前只支持 1.1。当 libyaml 支持 1.2 时,这将成为一个选项。来自 libyaml 文档...“version_directive - 使用 %YAML 指令指定的版本;唯一有效值是 1.1;可能为 NULL。” pyyaml.org/wiki/LibYAML
猜你喜欢
  • 2013-02-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多