Save key loading in YAML from file in Ruby

I want to keep the key order in a YAML file loaded from disk, processed in some way and written to disk.

Here is a basic example of loading YAML in Ruby (v1.8.7):

require 'yaml' configuration = nil File.open('configuration.yaml', 'r') do |file| configuration = YAML::load(file) # at this point configuration is a hash with keys in an undefined order end # process configuration in some way File.open('output.yaml', 'w+') do |file| YAML::dump(configuration, file) end 

Unfortunately, this will ruin the order of the keys in configuration.yaml after creating the hash. I cannot find a way to manage the data structure used by YAML::load() , for example. alib orderedmap .

I was not lucky to find a solution on the Internet.

+4
source share
3 answers

If you are stuck using 1.8.7 for any reason (like me), I resorted to using active_support/ordered_hash . I know that activesupport seems great, but they reorganized it in later versions, where you pretty much only need the part that you need in the file, and the rest is left unattended. Just gem install activesupport and enable it as shown below. Also, in your YAML file, be sure to use the omap declaration (and the hash array). Sample time!

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

This is what Ruby looks like behind it.

 # loader.rb # require 'yaml' require 'active_support/ordered_hash' # Load up the file into a Hash config = File.open('config.yml','r') { |f| YAML::load f } # So long as you specified an !!omap, this is actually a # YAML::PrivateClass, an array of Hashes puts config['months'].class # Parse through its value attribute, stick results in an OrderedHash, # and reassign it to our hash ordered = ActiveSupport::OrderedHash.new config['months'].value.each { |m| ordered[m.keys.first] = m.values.first } config['months'] = ordered 

I am looking for a solution that allows me to dig out Hash loaded from an .yml file .yml , look for those YAML::PrivateClass and convert them to ActiveSupport::OrderedHash . May I ask a question.

+2
source

Use Ruby 1.9.x. The previous version of Ruby does not preserve the order of the Hash keys, but 1.9 does.

+3
source

Someone came up with the same problem . There is a gem of an ordered hash . Note that this is not a hash; it subclasses the hash. You can try, but if you see a problem with YAML, you should consider upgrading to ruby1.9.

+1
source

All Articles