Skip to content

Instantly share code, notes, and snippets.

@drhuffman12
Created November 30, 2016 19:03
Show Gist options
  • Save drhuffman12/91c5965d309ec74052dbc546006136b5 to your computer and use it in GitHub Desktop.
Save drhuffman12/91c5965d309ec74052dbc546006136b5 to your computer and use it in GitHub Desktop.
utility methods for hashes
class HashUtils
# See also various flattening solutions at http://stackoverflow.com/questions/23521230/flattening-nested-hash-to-a-single-hash-with-ruby-rails
def self.flatten_hash(param, prefix='')
param.each_pair.reduce({}) do |a, (k, v)|
v.is_a?(Hash) ? a.merge(flatten_hash(v, "#{prefix}#{k}.")) : a.merge("#{prefix}#{k}".to_sym => v)
end
end
end
class Hash
def flatten(prefix)
HashUtils.flatten_hash(self, prefix='')
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment