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 want to get what is the difference between two hashes, you can do this:
h1 = {:a => 20, :b => 10, :c => 44}
h2 = {:a => 2, :b => 10, :c => "44"}
result = {}
h1.each {|k, v| result[k] = h2[k] if h2[k] != v }
p result #=> {:a => 2, :c => "44"}
Rails is deprecating the diff method.
For a quick one-liner:
hash1.to_s == hash2.to_s
How about another, simpler approach:
require 'fileutils'
FileUtils.cmp(file1, file2)
You can try the hashdiff gem, which allows deep comparison of hashes and arrays in the hash.
The following is an example:
a = {a:{x:2, y:3, z:4}, b:{x:3, z:45}}
b = {a:{y:3}, b:{y:3, z:30}}
diff = HashDiff.diff(a, b)
diff.should == [['-', 'a.x', 2], ['-', 'a.z', 4], ['-', 'b.x', 3], ['~', 'b.z', 45, 30], ['+', 'b.y', 3]]
You could use a simple array intersection, this way you can know what differs in each hash.
hash1 = { a: 1 , b: 2 }
hash2 = { a: 2 , b: 2 }
overlapping_elements = hash1.to_a & hash2.to_a
exclusive_elements_from_hash1 = hash1.to_a - overlapping_elements
exclusive_elements_from_hash2 = hash2.to_a - overlapping_elements
If you want a nicely formatted diff, you can do this:
# Gemfile
gem 'awesome_print' # or gem install awesome_print
And in your code:
require 'ap'
def my_diff(a, b)
as = a.ai(plain: true).split("\n").map(&:strip)
bs = b.ai(plain: true).split("\n").map(&:strip)
((as - bs) + (bs - as)).join("\n")
end
puts my_diff({foo: :bar, nested: {val1: 1, val2: 2}, end: :v},
{foo: :bar, n2: {nested: {val1: 1, val2: 3}}, end: :v})
The idea is to use awesome print to format, and diff the output. The diff won't be exact, but it is useful for debugging purposes.