Skip to content

Instantly share code, notes, and snippets.

@jdunck
Created August 5, 2015 03:59
Show Gist options
  • Save jdunck/6bf6363550c8d5c44ccf to your computer and use it in GitHub Desktop.
Save jdunck/6bf6363550c8d5c44ccf to your computer and use it in GitHub Desktop.
Flatten a Hash, preserving key namespacing
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