我有一个 YAML 文件,其中包含:
cat:
name: Cat
description: catlike reflexes
dog:
name: Dog
description: doggy breath
我想解析它并将描述分解成key1
这样key2
:
cat:
name: Cat
description: catlike reflexes
info:
key1: catlike
key2: reflexes
dog:
name: Dog
description: doggy breath
info:
key1: doggy
key2: breath
但是,由于某种原因,我不能正确地做到这一点。到目前为止,我尝试过的是下面代码的变体,我认为我过于复杂了:
# to get the original file's data
some_data = YAML.load(File.open("#{Rails.root}/config/some_data.yml"))
new_data = some_data.collect do |old_animal|
animal = old_animal.second
if animal && animal["description"]
new_blocks = Hash.new
blocks = animal["description"].split(" ")
new_blocks["key1"] = blocks.first
new_blocks["key2"] = blocks.second
animal["info"] = new_blocks
end
old_animal.second = animal
old_animal
end
# to write over the original file
File.write("#{Rails.root}/config/some_data.yml", new_data.to_yaml)