Reputation: 3583
I need to load a yaml file into Hash,
What should I do?
Upvotes: 43
Views: 55123
Reputation: 1032
You may run into a problem mentioned at this related question, namely, that the YAML file or stream specifies an object into which the YAML loader will attempt to convert the data into. The problem is that you will need a related Gem that knows about the object in question.
My solution was quite trivial and is provided as an answer to that question. Do this:
yamltext = File.read("somefile","r")
yamltext.sub!(/^--- \!.*$/,'---')
hash = YAML.load(yamltext)
In essence, you strip the object-classifier text from the yaml-text. Then you parse/load it.
Upvotes: 5
Reputation: 1281
A simpler version of venables' answer:
hash = YAML.load_file("file_path")
Upvotes: 30
Reputation: 85458
Use the YAML module:
http://ruby-doc.org/stdlib-1.9.3/libdoc/yaml/rdoc/YAML.html
node = YAML::parse( <<EOY )
one: 1
two: 2
EOY
puts node.type_id
# prints: 'map'
p node.value['one']
# prints key and value nodes:
# [ #<YAML::YamlNode:0x8220278 @type_id="str", @value="one", @kind="scalar">,
# #<YAML::YamlNode:0x821fcd8 @type_id="int", @value="1", @kind="scalar"> ]'
# Mappings can also be accessed for just the value by accessing as a Hash directly
p node['one']
# prints: #<YAML::YamlNode:0x821fcd8 @type_id="int", @value="1", @kind="scalar">
http://yaml4r.sourceforge.net/doc/page/parsing_yaml_documents.htm
Upvotes: 12
Reputation: 2594
I would use something like:
hash = YAML.load(File.read("file_path"))
Upvotes: 118