views:

68

answers:

2

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

+1  A: 

Use the YAML module:
http://ruby-doc.org/core/classes/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

NullUserException
A: 

I would use something like:

hash = YAML.load(File.read("file_path"))
vegetables
Depending on the usage, that's a potentially leaky solution. Symbols are interned and never garbage collected, so allowing for arbitrary symbolification of string data can lead to non-recoverable memory usage.If ActiveSupport is available, it's better to use `YAML.load(...).with_indifferent_access`. That'll let you access keys by string or symbol.
Chris Heald