I am trying to compare two Ruby Hashes using the following code:
#!/usr/bin/env ruby
require \"yaml\"
require \"active_support\"
file1 = YAML::load(File.op
If you need a quick and dirty diff between hashes which correctly supports nil in values you can use something like
def diff(one, other)
(one.keys + other.keys).uniq.inject({}) do |memo, key|
unless one.key?(key) && other.key?(key) && one[key] == other[key]
memo[key] = [one.key?(key) ? one[key] : :_no_key, other.key?(key) ? other[key] : :_no_key]
end
memo
end
end
I developed this to compare if two hashes are equal
def hash_equal?(hash1, hash2)
array1 = hash1.to_a
array2 = hash2.to_a
(array1 - array2 | array2 - array1) == []
end
The usage:
> hash_equal?({a: 4}, {a: 4})
=> true
> hash_equal?({a: 4}, {b: 4})
=> false
> hash_equal?({a: {b: 3}}, {a: {b: 3}})
=> true
> hash_equal?({a: {b: 3}}, {a: {b: 4}})
=> false
> hash_equal?({a: {b: {c: {d: {e: {f: {g: {h: 1}}}}}}}}, {a: {b: {c: {d: {e: {f: {g: {h: 1}}}}}}}})
=> true
> hash_equal?({a: {b: {c: {d: {e: {f: {g: {marino: 1}}}}}}}}, {a: {b: {c: {d: {e: {f: {g: {h: 2}}}}}}}})
=> false