Class: Hash

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

Instance Method Summary collapse

Instance Method Details

#supermerge(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"]}


30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/foreplay.rb', line 30

def supermerge(other_hash)
  raise "supermerge needs a Hash, not a #{other_hash.class}." unless other_hash.is_a?(Hash)

  new_hash = deep_dup

  other_hash.each_pair do |k, v|
    tv = new_hash[k]

    new_hash[k] = if tv.is_a?(Hash) && v.is_a?(Hash)
                    tv.supermerge(v)
                  elsif tv.is_a?(Array) || v.is_a?(Array)
                    Array.wrap(tv) + Array.wrap(v)
                  else
                    v
                  end
  end

  new_hash
end