load - Preserve key order loading YAML from a file in Ruby -


i want preserve order of keys in yaml file loaded disk, processed in way , written disk.

here basic example of loading yaml in ruby (v1.8.7):

require 'yaml'  configuration = nil file.open('configuration.yaml', 'r') |file|   configuration = yaml::load(file)   # @ point configuration hash keys in undefined order end  # process configuration in way  file.open('output.yaml', 'w+') |file|   yaml::dump(configuration, file) end 

unfortunately, destroy order of keys in configuration.yaml once hash built. cannot find way of controlling data structure used yaml::load(), e.g. alib's orderedmap.

i've had no luck searching web solution.

if you're stuck using 1.8.7 whatever reason (like am), i've resorted using active_support/ordered_hash. know activesupport seems big include, they've refactored in later versions pretty require part need in file , rest gets left out. gem install activesupport, , include shown below. also, in yaml file, sure use !!omap declaration (and array of hashes). example time!

# config.yml #  months: !!omap   - january: enero   - february: febrero   - march: marzo   - april: abril   - may: mayo 

here's ruby behind looks like.

# loader.rb #  require 'yaml' require 'active_support/ordered_hash'  # load file hash config = file.open('config.yml','r') { |f| yaml::load f }  # long specified !!omap, # yaml::privateclass, array of hashes puts config['months'].class  # parse through value attribute, stick results in orderedhash, # , reassign our hash ordered = activesupport::orderedhash.new config['months'].value.each { |m| ordered[m.keys.first] = m.values.first } config['months'] = ordered 

i'm looking solution allows me recursively dig through hash loaded .yml file, yaml::privateclass objects, , convert them activesupport::orderedhash. may post question on that.


Comments

Popular posts from this blog

c# - how to write client side events functions for the combobox items -

exception - Python, pyPdf OCR error: pyPdf.utils.PdfReadError: EOF marker not found -