How to parse a yaml file into ruby hashs and/or arrays?

48,338

Solution 1

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

Solution 2

I would use something like:

hash = YAML.load(File.read("file_path"))

Solution 3

A simpler version of venables' answer:

hash = YAML.load_file("file_path")

Solution 4

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.

Share:
48,338
Croplio
Author by

Croplio

Updated on October 25, 2020

Comments

  • Croplio
    Croplio over 3 years

    I need to load a yaml file into Hash,
    What should I do?