Class: Hash

Inherits:
Object
  • Object
show all
Defined in:
lib/distil/hash-additions.rb

Overview

Hash#deep_merge From: pastie.textmate.org/pastes/30372, Elliott Hird Source: gemjack.com/gems/tartan-0.1.1/classes/Hash.html This file contains extensions to Ruby and other useful snippits of code. Time to extend Hash with some recursive merging magic.

Instance Method Summary collapse

Instance Method Details

#deep_merge(hash) ⇒ Object

Merges self with another hash, recursively.

This code was lovingly stolen from some random gem: gemjack.com/gems/tartan-0.1.1/classes/Hash.html

Thanks to whoever made it.



16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/distil/hash-additions.rb', line 16

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

#deep_merge!(second) ⇒ Object

From: www.gemtacular.com/gemdocs/cerberus-0.2.2/doc/classes/Hash.html File lib/cerberus/utils.rb, line 42



35
36
37
38
39
40
41
42
43
# File 'lib/distil/hash-additions.rb', line 35

def deep_merge!(second)
  second.each_pair do |k,v|
    if self[k].is_a?(Hash) and second[k].is_a?(Hash)
      self[k].deep_merge!(second[k])
    else
      self[k] = second[k]
    end
  end
end