[英]Rails - Display difference between two Hashes
I have two Hashes hash1 and hash2.我有两个哈希 hash1 和 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: Rails 有 Hash#diff:
http://apidock.com/rails/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.编辑:但是,这已在 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.将 Unixmonkey 的答案、Chris Scott 的评论和
Hash.diff
现在已弃用的消息结合在一起。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.