Skip to content

Instantly share code, notes, and snippets.

@sawanoboly
Created February 17, 2012 10:28
Show Gist options
  • Save sawanoboly/1852505 to your computer and use it in GitHub Desktop.
Save sawanoboly/1852505 to your computer and use it in GitHub Desktop.
Compare keys in yaml files
def compare_yaml_hash(cf1, cf2, context = [])
case
when cf1.is_a?(Hash)
cf1.each do |key, value|
unless cf2.key?(key)
puts "Missing key : #{key} in path #{context.join(".")}"
next
end
value2 = cf2[key]
if (value.class != value2.class)
puts "Key value type mismatch : #{key} in path #{context.join(".")}"
next
end
if value.is_a?(Hash)
compare_yaml_hash(value, cf2[key], (context << key))
next
end
end
when cf1.is_a?(Array)
cf1.each do |key|
if key.is_a?(Hash)
compare_yaml_hash(key, cf2[key], (context << key))
next
end
end
end
end
@sawanoboly
Copy link
Author

require 'yaml'
aa = YAML.load_file("a.yml")

bb = YAML.load_file("b.yml")

compare_yaml_hash(aa,bb)
compare_yaml_hash(bb,aa)

@sawanoboly
Copy link
Author

@amencarini
Copy link

You need to pop the last element in context coming out of the subcycle of compare_yaml_hash

compare_yaml_hash(key, cf2[key], (context << key))  
context.pop
next

That would do the trick.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment