Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - Display difference between two Hashes

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?

like image 541
Clint Avatar asked Dec 25 '22 18:12

Clint


1 Answers

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}
like image 58
Unixmonkey Avatar answered Jan 07 '23 01:01

Unixmonkey