I need to load a yaml file into Hash,
What should I do?
views:
68answers:
2
+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
2010-08-14 01:40:35
A:
I would use something like:
hash = YAML.load(File.read("file_path"))
vegetables
2010-08-14 04:28:58
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
2010-08-14 05:53:25