我有一个用ruby命名的数组,我把值加载到yaml文件中,但是在file.yml中,它删除了%yaml1.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)在执行之前,头文件是存在的,但是在执行之后,它删除了它(%YAML1.1),并且所有的行都用#注释,所以我不会
发布于 2018-09-27 05:52:20
我想这就是你想要做的。
我假设您的yaml标题数组与您的数组对象匹配。
否则,如果只想将Enum#with_index数组的编号映射到文本,则可以使用类似yaml的内容。
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 - 3https://stackoverflow.com/questions/52524503
复制相似问题