Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>here is a slightly modified version from colin's. </p> <pre><code>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) &amp;&amp; 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 </code></pre> <p>It recurses into the hashes for more efficient left and right</p> <pre><code>{a: {c: 1, b: 2}, b: 2}.diff({a: {c: 2, b: 2}}) </code></pre> <p>returns</p> <pre><code>{:a=&gt;{:c=&gt;[1, 2]}, :b=&gt;[2, nil]} </code></pre> <p>instead of </p> <pre><code>{:a=&gt;[{:c=&gt;1, :b=&gt;2}, {:c=&gt;2, :b=&gt;2}], :b=&gt;[2, nil]} </code></pre> <p>Great idea colin</p> <p>here is how to apply the diff to the original hashes</p> <pre><code> 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 </code></pre> <p>so to make the left look like the right you run</p> <pre><code>{a: {c: 1, b: 2}, b: 2}.apply_diff({:a=&gt;{:c=&gt;[1, 2]}, :b=&gt;[2, nil]}) </code></pre> <p>to get </p> <pre><code>{a: {c: 2, b: 2}, b: nil} </code></pre> <p>to get exact we would have to go a little farther and record a difference between between nil and no key<br> and it would also be nice to shorten long arrays by just providing adds and removes</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload