Class: Hash

Inherits:
Object
  • Object
show all
Defined in:
lib/thefox-ext/ext/hash.rb

Instance Method Summary collapse

Instance Method Details

#merge_recursive(h2, level = 0, clone = true) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
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
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/thefox-ext/ext/hash.rb', line 4

def merge_recursive(h2, level = 0, clone = true)
  if !h2.is_a?(Hash)
    raise ArgumentError, "Argument is not a Hash -- #{h2.class} given"
  end

  has_subhashes = false

  h1 = self
  if clone
    # We want to modify only the clone.
    h1 = self.clone
  end

  # Iterate Hash 1
  h1.each do |k, v|
    if v.is_a?(Hash)
      has_subhashes = true

      # If Hash 2 also has the same key.
      if h2.has_key?(k)
        if h2[k].is_a?(Hash)
          # Inception! Go one level deeper.
          h1[k] = v.merge_recursive(h2[k], level + 1)
        else
          h1[k] = h2[k]
        end
      end
    else
      # Value of Hash 1 is no Subhash.

      # Only overwrite Hash 1 Value with Hash 2 Value
      # if a Hash 2 Key exist.
      if h2.has_key?(k)
        h1[k] = h2[k]
      end
    end
  end

  # Iterate Hash 2
  # Because we also want Key from Hash 2
  # which don't exist in Hash 1.
  h2.each do |k, v|
    if !h1.has_key?(k)
      h1[k] = v
    end
  end

  if !has_subhashes
    # If there are no subhashes merge
    # with existing merge function.
    h1.merge!(h2)
  end

  # Return h1 modified clone.
  return h1
end

#merge_recursive!(h2) ⇒ Object



61
62
63
# File 'lib/thefox-ext/ext/hash.rb', line 61

def merge_recursive!(h2)
  self.merge_recursive(h2, 0, false)
end