Created
March 2, 2015 19:10
-
-
Save beechnut/bb3d689845f8595a6517 to your computer and use it in GitHub Desktop.
Flatten hashes recursively
This file contains hidden or 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
# From http://stackoverflow.com/questions/16497719/flatten-a-nested-hash-in-ruby-on-rails | |
module Enumerable | |
def flatten_with_path(parent_prefix = nil) | |
res = {} | |
self.each_with_index do |elem, i| | |
if elem.is_a?(Array) | |
k, v = elem | |
else | |
k, v = i, elem | |
end | |
# assign key name for result hash | |
key = parent_prefix ? "#{parent_prefix}.#{k}" : k | |
if v.is_a? Enumerable | |
# recursive call to flatten child elements | |
res.merge!(v.flatten_with_path(key)) | |
else | |
res[key] = v | |
end | |
end | |
res | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment