I have a YAML file containing:
cat:
name: Cat
description: catlike reflexes
dog:
name: Dog
description: doggy breath
I want to parse it and break the description into key1
and key2
like so:
cat:
name: Cat
description: catlike reflexes
info:
key1: catlike
key2: reflexes
dog:
name: Dog
description: doggy breath
info:
key1: doggy
key2: breath
But, for some reason, I cannot do this correctly. What I've tried so far are variations of the code below, which I think I'm overcomplicating:
# 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)