41

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

Croplio
  • 3,433
  • 6
  • 31
  • 37
  • 4
    Please update your selected answer. The one you've selected does not answer your actual question (regardless of whether it's more informative or not) – Volte Apr 11 '14 at 16:08

4 Answers4

117

I would use something like:

hash = YAML.load(File.read("file_path"))
venables
  • 2,584
  • 2
  • 17
  • 17
27

A simpler version of venables' answer:

hash = YAML.load_file("file_path")
Dessa Simpson
  • 1,232
  • 1
  • 15
  • 30
12

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

Blake
  • 695
  • 9
  • 23
NullUserException
  • 83,810
  • 28
  • 209
  • 234
  • 9
    This tends to return Syck::Map (or similar objects), not hashes. Any way to have it return (or convert to) a regular ruby Hash? – elsurudo Apr 21 '13 at 19:37
5

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.

chocolateboy
  • 1,693
  • 1
  • 19
  • 21
Otheus
  • 785
  • 10
  • 18