Class: Hash
- Inherits:
-
Object
- Object
- Hash
- Defined in:
- lib/extensions/hash.rb
Instance Method Summary collapse
-
#deep_merge(hash) ⇒ Object
Merges self with another hash, recursively.
-
#deep_merge!(second) ⇒ Object
From: www.gemtacular.com/gemdocs/cerberus-0.2.2/doc/classes/Hash.html File lib/cerberus/utils.rb, line 42.
-
#deep_merge2(other) ⇒ Object
cf.
- #deep_merge3(second) ⇒ Object
- #keep_merge(hash) ⇒ Object
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.
18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
# File 'lib/extensions/hash.rb', line 18 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
37 38 39 40 41 42 43 44 45 |
# File 'lib/extensions/hash.rb', line 37 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 |
#deep_merge2(other) ⇒ Object
51 52 53 54 55 56 57 58 59 |
# File 'lib/extensions/hash.rb', line 51 def deep_merge2(other) deep_proc = Proc.new { |k, s, o| if s.kind_of?(Hash) && o.kind_of?(Hash) next s.merge(o, &deep_proc) end next o } merge(other, &deep_proc) end |
#deep_merge3(second) ⇒ Object
62 63 64 65 66 67 68 69 70 |
# File 'lib/extensions/hash.rb', line 62 def deep_merge3(second) # From: http://www.ruby-forum.com/topic/142809 # Author: Stefan Rusterholz merger = proc { |key,v1,v2| Hash === v1 && Hash === v2 ? v1.merge(v2, &merger) : v2 } self.merge(second, &merger) end |
#keep_merge(hash) ⇒ Object
73 74 75 76 77 78 79 80 81 82 83 84 |
# File 'lib/extensions/hash.rb', line 73 def keep_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].keep_merge(hash[key]) next end #target[key] = hash[key] target.update(hash) { |key, *values| values.flatten.uniq } end target end |