Reputation: 323
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
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
Reputation: 84353
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
Reputation: 146073
I imagine you know this and just want a different solution, but for the record I believe you have exactly two choices.
- a: b c: d - e: f g: h
x: a: b c: d y: e: f g: h
Upvotes: 0