Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby YAML Multiple Documents

Here is my YAML file, 'test.yml':

---
alpha: 100.0
beta: 200.0
gama: 300.0
--- 3
...

The first document is a hash.

The second document is an integer.

I am trying to load these to a Ruby program as a hash and an integer.

Here is my current attempt:

require 'yaml'

variables = YAML.load_file('test.yml')
puts variables.inspect
like image 974
labelcd6 Avatar asked Oct 11 '13 18:10

labelcd6


2 Answers

To access multiple YAML documents in a single file, use the load_stream method (as already mentioned by "matt" in a comment to one of the other answers):

YAML.load_stream(File.read('test.yml')) do |document|
  puts document
end
like image 177
Markus Miller Avatar answered Oct 18 '22 19:10

Markus Miller


The Tin Man is correct that the OP should not be using multiple documents for his specific problem; however, the situation of multiple documents in a YAML stream does occur in practice, for example when multiple YAML documents are appended to a single file, so it's worth knowing how to deal with it.

require 'yaml'

yaml = <<EOT
---
alpha: 100.0
beta: 200.0
gama: 300.0
---
int: 3
...
EOT

loop do
  puts YAML.load(yaml)
  break if !yaml.sub!(/(?<!#)(-{3}.+?(?=-{3})\n?){1}/m,'')
  break if yaml.empty?
end

# >> {"alpha"=>100.0, "beta"=>200.0, "gama"=>300.0}
# >> {"int"=>3}
like image 39
Penn Taylor Avatar answered Oct 18 '22 18:10

Penn Taylor