Class: Hash

Inherits:
Object
  • Object
show all
Defined in:
lib/safe_merge.rb

Overview

The Hash class

Instance Method Summary collapse

Instance Method Details

#safe_merge(other) ⇒ Object

Safely merges the current Hash with an ‘other’ Hash.



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/safe_merge.rb', line 6

def safe_merge(other)
  all_keys = keys | other.keys
  result_hash = {}

  all_keys.each do |key|
    hash_value = {}

    if key? key
      value = self[key]
      hash_value = value unless value.nil?
    end

    if other.key? key
      value = other[key]
      hash_value = hash_value.merge(value) unless value.nil?
    end

    result_hash[key] = hash_value
  end

  result_hash
end