Created
August 5, 2015 03:59
-
-
Save jdunck/6bf6363550c8d5c44ccf to your computer and use it in GitHub Desktop.
Flatten a Hash, preserving key namespacing
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
def flattened_hash(h, namespace = '', memo = {}) | |
h.reduce(memo) { |memo, (key, value)| | |
if value.instance_of?(Hash) | |
memo.merge!(flattened_hash(value, "#{namespace}#{key}_", memo)) | |
else | |
memo["#{namespace}#{key}"] = value | |
end | |
memo | |
} | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment