Created
March 5, 2015 04:30
-
-
Save m5rk/1ad633281debcebf93cc to your computer and use it in GitHub Desktop.
functional flatten_hash
This file contains 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
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 |
flat_map
will help out a bit here too
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
I prefer
value.respond_to?(:keys)
instead ofvalue.is_a?(Hash)
, because who really cares whether it is a Hash? All we really care about is whether it responds to:keys
(and:values
).