Class: Hash

Inherits:
Object
  • Object
show all
Defined in:
lib/opennebula/flow/validator.rb

Direct Known Subclasses

VCenterConf

Instance Method Summary collapse

Instance Method Details

#deep_merge(other_hash) ⇒ Hash

Returns a new hash containing the contents of other_hash and the

contents of self. If the value for entries with duplicate keys
is a Hash, it will be merged recursively, otherwise it will be that
of other_hash.

Examples:

Merging two hashes

h1 = {:a => 3, {:b => 3, :c => 7}}
h2 = {:a => 22, c => 4, {:b => 5}}

h1.deep_merge(h2) #=> {:a => 22, c => 4, {:b => 5, :c => 7}}

Parameters:

Returns:

  • (Hash)

    Containing the merged values



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/opennebula/flow/validator.rb', line 34

def deep_merge(other_hash)
     target = dup

     other_hash.each do |hash_key, hash_value|
         if hash_value.is_a?(Hash) and self[hash_key].is_a?(Hash)
             target[hash_key] = self[hash_key].deep_merge(hash_value)
         elsif hash_value.is_a?(Array) and self[hash_key].is_a?(Array)
             hash_value.each_with_index { |elem, i|
                 if self[hash_key][i].is_a?(Hash) and elem.is_a?(Hash)
                     target[hash_key][i] = self[hash_key][i].deep_merge(elem)
                 else
                     target[hash_key] = hash_value
                 end
             }
         else
             target[hash_key] = hash_value
         end
     end

     target
end