Skip to content

Instantly share code, notes, and snippets.

@DiegoSalazar
Created January 6, 2015 17:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DiegoSalazar/4c32d057bf8db95dd681 to your computer and use it in GitHub Desktop.
Save DiegoSalazar/4c32d057bf8db95dd681 to your computer and use it in GitHub Desktop.
Flatten an arbitrarily nested hash into a flat hash with dotted key names
a = { a: 1, b: { c: 2, d: { e: 3 }}}
# define a recursive proc:
flatten_keys = -> (h, prefix = "") do
@flattened_keys ||= {}
h.each do |key, value|
# Here we check if there's "sub documents" by asking if the value is a Hash
# we also pass in the name of the current prefix and key and append a . to it
if value.is_a? Hash
flatten_keys.call value, "#{prefix}#{key}."
else
# if not we concatenate the key and the prefix and add it to the @flattened_keys hash
@flattened_keys["#{prefix}#{key}"] = value
end
end
@flattened_keys
end
flattened = flatten_keys.call a
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment