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
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
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With