I have two Hashes hash1 and hash2. Both have the same keys. I need to display the two hashes side by side with the difference between the hashes highlighted in a different color.
How can I do it?
Rails has Hash#diff:
http://apidock.com/rails/Hash/diff
{1 => 2}.diff(1 => 2) # => {}
{1 => 2}.diff(1 => 3) # => {1 => 2}
{}.diff(1 => 2) # => {1 => 2}
{1 => 2, 3 => 4}.diff(1 => 2) # => {3 => 4}
EDIT: However, this was removed in Rails 4.1. To get the same result in a more modern project you can use this method, which is derived from the above.
def hash_diff(first, second)
first.
dup.
delete_if { |k, v| second[k] == v }.
merge!(second.dup.delete_if { |k, v| first.has_key?(k) })
end
hash_diff({1 => 2}, {1 => 2}) # => {}
hash_diff({1 => 2}, {1 => 3}) # => {1 => 2}
hash_diff({}, {1 => 2}) # => {1 => 2}
hash_diff({1 => 2, 3 => 4}, {1 => 2}) # => {3 => 4}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With