Created
September 13, 2012 05:35
-
-
Save hide24/3712104 to your computer and use it in GitHub Desktop.
recursive merge of Hash
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Hash | |
def rmerge(other) | |
new_hash = {} | |
keys = (self.keys + other.keys).uniq | |
keys.each do |k| | |
if other.key?(k) | |
if self.key?(k) && self[k].kind_of?(Hash) | |
new_hash[k] = self[k].rmerge(other[k]) | |
else | |
new_hash[k] = other[k] | |
end | |
else | |
new_hash[k] = self[k] | |
end | |
end | |
new_hash | |
end | |
end | |
require 'yaml' | |
org_str = <<-EOS | |
en: | |
activerecord: | |
models: | |
metadata: "Metadata" | |
attributes: | |
metadata: | |
application_base_id: "ID Based on Application Form" | |
entity_id: "entityID" | |
certification: "Certificate" | |
status: "Status" | |
EOS | |
new_str = <<-EOS | |
en: | |
activerecord: | |
attributes: | |
metadata: | |
contact_person_name: "Name (English)" | |
contact_person_mail: "E-mail Address" | |
EOS | |
org_yaml = YAML.load(org_str) | |
new_yaml = YAML.load(new_str) | |
merged_yaml = org_yaml.rmerge(new_yaml) | |
puts YAML.dump(merged_yaml) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment