这里是科林的一个稍作修改的版本。
class Hash
def diff(other)
(self.keys + other.keys).uniq.inject({}) do |memo, key|
unless self[key] == other[key]
if self[key].kind_of?(Hash) && other[key].kind_of?(Hash)
memo[key] = self[key].diff(other[key])
else
memo[key] = [self[key], other[key]]
end
end
memo
end
end
end
递归到哈希值进行更有效的左侧和右侧
{a: {c: 1, b: 2}, b: 2}.diff({a: {c: 2, b: 2}})
回报
{:a=>{:c=>[1, 2]}, :b=>[2, nil]}
,而不是
{:a=>[{:c=>1, :b=>2}, {:c=>2, :b=>2}], :b=>[2, nil]}
好主意科林
这里是如何的DIFF向原散列
def apply_diff!(changes, direction = :right)
path = [[self, changes]]
pos, local_changes = path.pop
while local_changes
local_changes.each_pair {|key, change|
if change.kind_of?(Array)
pos[key] = (direction == :right) ? change[1] : change[0]
else
path.push([pos[key], change])
end
}
pos, local_changes = path.pop
end
self
end
def apply_diff(changes, direction = :right)
cloned = self.clone
path = [[cloned, changes]]
pos, local_changes = path.pop
while local_changes
local_changes.each_pair {|key, change|
if change.kind_of?(Array)
pos[key] = (direction == :right) ? change[1] : change[0]
else
pos[key] = pos[key].clone
path.push([pos[key], change])
end
}
pos, local_changes = path.pop
end
cloned
end
所以做出向左的样子正确运行
{a: {c: 1, b: 2}, b: 2}.apply_diff({:a=>{:c=>[1, 2]}, :b=>[2, nil]})
得到
{a: {c: 2, b: 2}, b: nil}
得到确切的说,我们必须走得更远一点,记录无钥匙和无钥匙之间的区别
,它也将很好,通过只提供添加和删除来缩短长阵列
为了我的目的,我并不特别在乎,因为我真的只需要知道哪些字段已更改。如果我使用AR,这不会是一个问题,但是所有内容都是通过数据层抽象到CouchDB,因此我发现自己需要重新发明轮子,可以说是为了某些功能。 尽管感谢您的建议。 – Chelsea 2009-11-19 22:02:29
哪一个当然对应于你的“暴力”评论,但我觉得它很有用,而不是那么可怕或不雅。 – 2009-11-19 22:02:55
这种方法不会注意到'other'哈希中的其他键也不能够告诉键没有值是'nil',用于改进版本检查http://stackoverflow.com/a/19184270/54247 – dolzenko 2013-10-04 14:52:05