我可以操作 yaml 文件并再次将它们写出来吗 [英] Can I manipulate yaml files and write them out again

查看:36
本文介绍了我可以操作 yaml 文件并再次将它们写出来吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个值映射,键是文件名,值是数组字符串.我有对应的文件

I have a map of values, the key is a filename and the value is an array strings. I have the corresponding files

我将如何加载文件并创建一个包含数组值的固定 yaml 值,无论该值是否已存在

how would I load the file and create a fixed yaml value which contains the value of the array whether or not the value already exists

例如

YAML (file.yaml)

YAML (file.yaml)

trg::azimuth:
-extra
-intra
-lateral

trg::azimuth: 
  [extra,intra,lateral]

来自

红宝石

{"file.yaml" => ["extra","intra","lateral"]}

推荐答案

YAML 文档 没有很好地涵盖其方法,但确实说明了

The YAML documentation doesn't cover its methods very well, but does say

底层实现是 libyaml 包装器 Psych.

The underlying implementation is the libyaml wrapper Psych.

心理文档是 YAML 的基础,涵盖读取、解析和发出 YAML.

The Psych documentation, which underlies YAML, covers reading, parsing, and emitting YAML.

基本流程如下:

require 'yaml'

foo = {"file.yaml" => ["extra","intra","lateral"]}
bar = foo.to_yaml
# => "---\nfile.yaml:\n- extra\n- intra\n- lateral\n"

这是生成的、序列化的 bar 变量在写入时的样子:

And here's what the generated, serialized bar variable looks like if written:

puts bar
# >> ---
# >> file.yaml:
# >> - extra
# >> - intra
# >> - lateral

这是 YAML 解析器需要的格式:

That's the format a YAML parser needs:

baz = YAML.load(bar)
baz
# => {"file.yaml"=>["extra", "intra", "lateral"]}

此时哈希已经往返,从 Ruby 哈希到 YAML 序列化字符串,再返回到 Ruby 哈希.

At this point the hash has gone round-trip, from a Ruby hash, to a YAML-serialized string, back to a Ruby hash.

使用 Ruby 的 File.write 方法很容易将 YAML 写入文件:

Writing YAML to a file is easy using Ruby's File.write method:

File.write(foo.keys.first, foo.values.first.to_yaml)

foo.each do |k, v| 
  File.write(k, v.to_yaml)
end

这会生成一个名为file.yaml"的文件,其中包含:

Which results in a file named "file.yaml", which contains:

---
- extra
- intra
- lateral

要读取和解析文件,请使用 YAML 的 load_file 方法.

To read and parse a file, use YAML's load_file method.

foo = YAML.load_file('file.yaml')
# => ["extra", "intra", "lateral"]

"我如何解析 YAML 文件?" 可能以及本页右侧的其他相关"链接.

"How do I parse a YAML file?" might be of use, as well as the other "Related" links on the right side of this page.

这篇关于我可以操作 yaml 文件并再次将它们写出来吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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