Created
November 30, 2016 19:03
-
-
Save drhuffman12/91c5965d309ec74052dbc546006136b5 to your computer and use it in GitHub Desktop.
utility methods for hashes
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
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