Created
January 6, 2015 17:11
-
-
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
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
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