0

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

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

e.g.

YAML (file.yaml)

trg::azimuth:
-extra
-intra
-lateral

or

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

from

RUBY

{"file.yaml" => ["extra","intra","lateral"]}
Paddy Carroll
  • 528
  • 3
  • 20

1 Answers1

1

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

The underlying implementation is the libyaml wrapper Psych.

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

Here's the basic process:

require 'yaml'

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

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

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

That's the format a YAML parser needs:

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

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

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

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

or

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

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

---
- extra
- intra
- lateral

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

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

"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.

Community
  • 1
  • 1
the Tin Man
  • 158,662
  • 42
  • 215
  • 303