Class: Hash

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

Overview

adding a method to hash to allow to merge two hases only by modifying aready existing entries

Instance Method Summary collapse

Instance Method Details

#merge_no_new(other_hash) ⇒ Hash

Merges another hash by updating only the values for keys that already exist. It does not add new keys from the other hash. The merge is recursive for nested hashes.

Parameters:

  • other_hash (Hash)

    The hash to merge from.

Returns:

  • (Hash)

    The new, merged hash.



10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/defmastership/hash_merge_no_new.rb', line 10

def merge_no_new(other_hash)
  # We use #merge with a block to handle key "collisions".
  # We only merge the keys from `other_hash` that already exist in `self`
  # by using `other_hash.slice(*keys)`.
  merge(other_hash.slice(*keys)) do |_key, old_val, new_val|
    if old_val.is_a?(Hash) && new_val.is_a?(Hash)
      # Recursive call if both values are hashes
      old_val.merge_no_new(new_val)
    else
      # else, we simply take the new value
      new_val
    end
  end
end