VocabReminder
Easily build a great vocabulary without studying! Now on the App Store!
Click here for more info about the app

How to Merge a YAML File Into a Single Hash in Ruby

       
require 'yaml'

# Nested YAML structure from something-nested.yml
#
# nested:
#   key: value
#   key_two: value_two

# Procedural Approach to building a single Hash from nested YAML data structure.
@yaml = YAML.load_file("something-nested.yml")

@container = {} 
@yaml.values.each do |value|
    @container.merge!(value)
end

@container.inspect
# => {:key => value, :key_two => value_two}


# And a one liner...
@yaml.values.inject({}) { |container, value| container.merge(value) }
# => {:key => value, :key_two => value_two}
Tagged w/ #data structures #hash #how to #programming #ruby #yamlruby