Class: Foreplay::Utility
- Inherits:
-
Object
- Object
- Foreplay::Utility
- Defined in:
- lib/foreplay/utility.rb
Class Method Summary collapse
-
.supermerge(hash, other_hash) ⇒ Object
Returns a new hash with
hashandother_hashmerged recursively, including arrays.
Class Method Details
.supermerge(hash, other_hash) ⇒ Object
Returns a new hash with hash and other_hash merged recursively, including arrays.
h1 = { x: { y: [4,5,6] }, z: [7,8,9] }
h2 = { x: { y: [7,8,9] }, z: 'xyz' }
h1.supermerge(h2)
#=> {:x=>{:y=>[4, 5, 6, 7, 8, 9]}, :z=>[7, 8, 9, "xyz"]}
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
# File 'lib/foreplay/utility.rb', line 9 def self.supermerge(hash, other_hash) fail 'supermerge only works if you pass two hashes. '\ "You passed a #{hash.class} and a #{other_hash.class}." unless hash.is_a?(Hash) && other_hash.is_a?(Hash) new_hash = hash.deep_dup.with_indifferent_access other_hash.each_pair do |k, v| tv = new_hash[k] if tv.is_a?(Hash) && v.is_a?(Hash) new_hash[k] = Foreplay::Utility.supermerge(tv, v) elsif tv.is_a?(Array) || v.is_a?(Array) new_hash[k] = Array.wrap(tv) + Array.wrap(v) else new_hash[k] = v end end new_hash end |