Module: Collapsium::RecursiveMerge
- Included in:
- UberHash
- Defined in:
- lib/collapsium/recursive_merge.rb
Overview
Provides recursive merge functions for hashes.
Instance Method Summary collapse
-
#recursive_merge(other, overwrite = true) ⇒ Object
Same as
dup.recursive_merge!. -
#recursive_merge!(other, overwrite = true) ⇒ Object
Recursively merge
:otherinto this Hash.
Instance Method Details
#recursive_merge(other, overwrite = true) ⇒ Object
Same as dup.recursive_merge!
51 52 53 54 55 |
# File 'lib/collapsium/recursive_merge.rb', line 51 def recursive_merge(other, overwrite = true) copy = dup copy.extend(RecursiveMerge) return copy.recursive_merge!(other, overwrite) end |
#recursive_merge!(other, overwrite = true) ⇒ Object
Recursively merge :other into this Hash.
This starts by merging the leaf-most Hash entries. Arrays are merged by addition.
For everything that’s neither Hash or Array, if the :overwrite parameter is true, the entry from :other is used. Otherwise the entry from :self is used.
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
# File 'lib/collapsium/recursive_merge.rb', line 26 def recursive_merge!(other, overwrite = true) if other.nil? return self end merger = proc do |_, v1, v2| # rubocop:disable Style/GuardClause if v1.is_a? Hash and v2.is_a? Hash next v1.merge(v2, &merger) elsif v1.is_a? Array and v2.is_a? Array next v1 + v2 end if overwrite next v2 else next v1 end # rubocop:enable Style/GuardClause end merge!(other, &merger) end |