Skip to content

Instantly share code, notes, and snippets.

@beechnut
Created March 2, 2015 19:10
Show Gist options
  • Save beechnut/bb3d689845f8595a6517 to your computer and use it in GitHub Desktop.
Save beechnut/bb3d689845f8595a6517 to your computer and use it in GitHub Desktop.
Flatten hashes recursively
# 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