Skip to content

Instantly share code, notes, and snippets.

@m5rk
Created March 5, 2015 04:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save m5rk/1ad633281debcebf93cc to your computer and use it in GitHub Desktop.
Save m5rk/1ad633281debcebf93cc to your computer and use it in GitHub Desktop.
functional flatten_hash
def flatten_hash(hash)
hash.keys + hash.values.select do |value|
value.respond_to?(:keys)
end.map do |hash|
flatten_hash(hash)
end.flatten
end
@jah2488
Copy link

jah2488 commented Mar 7, 2015

I like the functional approach. My own is pretty much the same.

def flatten_hash(hash)
  hash.keys.concat(hash.values.select { |v| v.respond_to?(:keys) }.flat_map(&method(:flatten_hash)))
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment