Module: Diff

Included in:
Array, Hash
Defined in:
lib/diff.rb

Instance Method Summary collapse

Instance Method Details

#diff(other, recursive = true) ⇒ Object



11
12
13
# File 'lib/diff.rb', line 11

def diff(other, recursive=true)
  gen_diff(other, recursive) {|a, b| a == b}
end

#gen_diff(other, recursive = true, &comp) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/diff.rb', line 15

def gen_diff(other, recursive=true, &comp)
  result = {
    :similar => {},
    :different => {},
    :missing => {},
    :additional => {}
  }
  if not other.is_a?(self.class)
    result[:different] = {:self => self.class, :other => other.class}
    return result
  end
  self.each_pair do |k, v|
    if other.has_key?(k)
      if comp[v, other[k]]
        result[:similar][k] = v
      else
        if recursive and v.respond_to?(:gen_diff)
          diff_result = v.gen_diff(other[k], recursive, &comp)
        else
          diff_result = {:self => v, :other => other[k]}
        end
        result[:different][k] = diff_result unless diff_result.no_diff?
      end
    else
      result[:additional][k] = v
    end
  end
  other.each_pair do |k, v|
    if not self.has_key?(k)
      result[:missing][k] = v
    end
  end
  result
end

#no_diff?Boolean

Returns:

  • (Boolean)


50
51
52
# File 'lib/diff.rb', line 50

def no_diff?
  self[:different] == {} and self[:missing] == {} and self[:additional] == {}
end