简体   繁体   中英

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?

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}

Bringing together Unixmonkey answer, Chris Scott's comment and the news that Hash.diff is now deprecated.

Patching Hash

class Hash
  def diff(compare_to)
    self
      .reject { |k, v| compare_to[k] == v }
      .merge!(compare_to.reject { |k, _v| self.key?(k) })
  end
end

Stand-alone

def hash_diff(a, b)
  a
    .reject { |k, v| b[k] == v }
    .merge!(b.reject { |k, _v| a.key?(k) })
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM