Deep comparison of Ruby Hash objects
Add this line to your application's Gemfile:
gem 'hash_comp'
And then execute:
$ bundle
Or install it yourself as:
$ gem install hash_comp
Easily find the differences between two Ruby hashes.
left = {
foo: 'bar',
bar: 'foo',
nested: {
foo: 'bar',
bar: {
one: 'foo1'
}
},
num: 1
}
right = {
foo: 'bar2',
bar: 'foo2',
nested: {
foo: 'bar2',
bar: {
two: 'foo2'
}
},
word: 'monkey'
}
hash_diff = HashComp::Comparison.new( left, right )
Comparison#diff returns the left and right side differences
hash_diff.diff # => { foo: ["bar", "bar2"], bar: ["foo", "foo2"], nested: { foo: ["bar", "bar2"], bar: { one: ["foo1", nil], two: [nil, "foo2"] } }, num: [1, nil], word: [nil, "monkey"] }
Comparison#left_diff returns only the left side differences
hash_diff.left_diff # => { foo: "bar2", bar: "foo2", nested: { foo: "bar2", bar: { one: nil, two: "foo2" } }, num: nil, word: "monkey" }
Comparison#right_diff returns only the right side differences
hash_diff.right_diff # => { foo: "bar", bar: "foo", nested: { foo: "bar", bar: { one: "foo1", two: nil } }, num: 1, word: nil }
You can also use these shorthand methods
HashComp.diff(left, right)
HashComp.left_diff(left, right)
HashComp.right_diff(left, right)
Hash#diff is not provided by default, and monkey patching is frowned upon by some, but to provide a one way shorthand call HashComp.patch!
# run prior to implementation
HashComp.patch!
left = { foo: 'bar', num: 1 }
right = { foo: 'baz', num: 1 }
left.diff(right) # => { foo: 'baz' }
Authored by the Engineering Team of Coding ZEAL
Copyright (c) 2017 Zeal, LLC. Licensed under the MIT license.
- Fork it
- Create your feature branch (
git checkout -b my-new-feature
) - Commit your changes (
git commit -am 'Add some feature'
) - Push to the branch (
git push origin my-new-feature
) - Create new Pull Request