Class: Hash
- Inherits:
-
Object
- Object
- Hash
- 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
-
#merge_no_new(other_hash) ⇒ Hash
Merges another hash by updating only the values for keys that already exist.
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.
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 |