Class: Hash

Inherits:
Object
  • Object
show all
Defined in:
lib/context-io/core_ext/hash.rb

Overview

Hash extensions

This is borrowed from ActiveSupport. We don’t want the entire ActiveSupport library (it’s huge), so we’ll just add this method.

Instance Method Summary collapse

Instance Method Details

#deep_merge(hash) ⇒ Hash

Merge self with another hash recursively

Examples:

Merge two hashes with some common keys

a_hash = { :foo => :bar, :baz => { :foobar => "hey" }}
another_hash = { :foo => :foobar, :baz => { :foo => :bar }}
a_hash.deep_merge(another_hash)
# => { :foo => :foobar, :baz => { :foobar => "hey", :foo => :bar }}

Parameters:

  • hash (Hash)

    The hash to merge into this one.

Returns:

  • (Hash)

    The given hash merged recursively into this one.



19
20
21
22
23
24
25
26
27
28
29
# File 'lib/context-io/core_ext/hash.rb', line 19

def deep_merge(hash)
  target = self.dup
  hash.keys.each do |key|
    if hash[key].is_a?(Hash) && self[key].is_a?(Hash)
      target[key] = target[key].deep_merge(hash[key])
      next
    end
    target[key] = hash[key]
  end
  target
end