super_noobling
super_noobling

Reputation: 323

How can I read multiple documents from a YAML file?

I want to make a YAML file that consists of only hashes. However, I cannot iterate over it. When I try to load the YAML file with:

YAML.load_file('yamlFile.yml') 

it returns only the first hash in the file. Here is an example file I would like to create:

---
:reach_hypo: true
:liquid: true
---
:reach_hypo: true
:liquid: false
---
:reach_hypo: true
:liquid: true 

If I load the above file, I get:

{reach_hypo: true, liquid: true}

The only workaround I have found is to add all the hashes into an array, then write it to the YAML file. Is there a better way, such as a YAML method, to iterate over the YAML file?

Upvotes: 3

Views: 3517

Answers (3)

rccursach
rccursach

Reputation: 315

You can try using Psych. It has been around since 1.9.3 but i didn't notice it until today. uses libyaml for parsing. ruby-doc

I tried the following code and works as expected:

require 'psych'

hash_arr = Psych.load_stream(File.read('yamlFile.yml'))
#=> [{:reach_hypo=>true, :liquid=>true}, {:reach_hypo=>true, :liquid=>false}, {:reach_hypo=>true, :liquid=>true}]

Upvotes: 0

Todd A. Jacobs
Todd A. Jacobs

Reputation: 84353

Read Multiple YAML Documents From Single File as Streams

You can use YAML::load_stream to read multiple documents from a single file. For example:

require 'yaml'

array = []
YAML.load_stream(File.read 'test.yml') { |doc| array << doc }
array

#=> [{:reach_hypo=>true, :liquid=>true}, {:reach_hypo=>true, :liquid=>false}, {:reach_hypo=>true, :liquid=>true}]

Upvotes: 10

DigitalRoss
DigitalRoss

Reputation: 146073

I imagine you know this and just want a different solution, but for the record I believe you have exactly two choices.

  1. Make an array of hashes.
    - a: b
      c: d
    - e: f
      g: h
  1. Use a two level hash, i.e, name each second-level hash and iterate over the keys in the top level.
    x:
      a: b
      c: d
    y:
      e: f
      g: h

Upvotes: 0

Related Questions