Created
December 28, 2010 19:12
-
-
Save benolee/757575 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# I just ripped off the deep_merge core extension from activesupport. | |
# The file is 'activesupport-3.0.3/lib/active_support/core_ext/hash/deep_merge.rb' | |
class Hash | |
# Returns a new hash with +self+ and +other_hash+ merged recursively. | |
def deep_merge(other_hash) | |
dup.deep_merge!(other_hash) | |
end | |
# Returns a new hash with +self+ and +other_hash+ merged recursively. | |
# Modifies the receiver in place. | |
def deep_merge!(other_hash) | |
other_hash.each_pair do |k,v| | |
tv = self[k] | |
self[k] = tv.is_a?(Hash) && v.is_a?(Hash) ? tv.deep_merge(v) : v | |
end | |
self | |
end | |
end | |
def thingajig hash | |
new_hash = {} | |
hash.each_pair do |key, value| | |
tokens = key.split('.') | |
tokens[-1] = Hash[tokens[-1],value] | |
nested_hash = tokens.push(Hash[*tokens.pop(2)]) until tokens.length == 1 | |
new_hash.deep_merge!(nested_hash[0]) | |
end | |
return new_hash | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment