Skip to content

Instantly share code, notes, and snippets.

@dplummer
Created May 3, 2013 20:40
Show Gist options
  • Save dplummer/5513903 to your computer and use it in GitHub Desktop.
Save dplummer/5513903 to your computer and use it in GitHub Desktop.
Compare two nested hashes
def compare_hashes(hash_a, hash_b, parent_keys = [])
keys_in_both = hash_a.keys & hash_b.keys
parent_name = parent_keys.map{|k| "['#{k}']"}.join
keys_in_both.each do |key|
if hash_a[key] != hash_b[key]
if hash_a[key].is_a?(Hash) && hash_b[key].is_a?(Hash)
compare_hashes(hash_a[key], hash_b[key], parent_keys + [key])
else
puts "#{parent_name} Key differs: #{key}"
end
end
end
hash_a_keys = hash_a.keys.reject {|k| hash_a[k].blank?}
hash_b_keys = hash_b.keys.reject {|k| hash_b[k].blank?}
unless (hash_a_keys - hash_b_keys).empty?
puts "#{parent_name} Keys just in A: #{hash_a_keys - hash_b_keys}"
end
unless (hash_b_keys - hash_a_keys).empty?
puts "#{parent_name} Keys just in B: #{hash_b_keys - hash_a_keys}"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment