I have a YAML document which I believe is valid (at least it would be
representable in XML):
If Ruby can’t read it, it’s not valid. SCNR
The problem is that using YAML.read on this produces a Hash in which
only one item occurs because (naturally) it has to be unique.
How can one traverse the nodes in a YAML document like this?
You could parse it like any ol’ text file, and build your Hash by
hand, with anything ending in a colon being a Hash key, whereas
anything that appears multiple times become a nested Hash with the key
that would normally be overwritten becoming the key to the nested
hash, and the, in your example, product becomes the nested Hash’s
keys.
Though the folk I have met,
(Ah, how soon!) they forget
When I’ve moved on to some other place,
There may be one or two,
When I’ve played and passed through,
Who’ll remember my song or my face.
Rather than having multiple keys that are the same (which doesn’t work
since
this is a hash data structure), you instead use an Array. I find an
easier
way to figure out how things should look it is to go from data that you
want
(what should it look like after being read), then dump it, and examine
the
results.
Thanks Josh for the detailed reply. Looking at the YAML in your first
reply though, I have to wonder: You end up with duplicate keys under the
items node, and if you load that with YAML, won’t you have the same
problem of only one product and one quantity remaining?
In any case, I am trying to cater for the situation where the creation
of the file is out of my control, i.e. I am receiving it from an
external source.
Actually that document is invalid.
The YAML spec [1] says about mappings:
The content of a mapping node is an unordered set of key: value node
pairs, with the restriction that each of the keys is unique.
Thanks Josh for the detailed reply. Looking at the YAML in your first
reply though, I have to wonder: You end up with duplicate keys under the
items node, and if you load that with YAML, won’t you have the same
problem of only one product and one quantity remaining?
A key is the name you use to refer to that set of data. Perhaps you mean
that I end up with two items, but you will notice they are not accessed
by
name. Each item is accessed by position rather than key, because it is
an
Array rather than a Hash, so it does not have the clashing keys problem.
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.