Last active
September 28, 2015 20:07
-
-
Save JasonTrue/f6ef2350d08ab349dc76 to your computer and use it in GitHub Desktop.
Flatten a hash structure
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={}, context="", new_hash={}) | |
hash.each do |key, value| | |
flattened_key = context.empty? ? key : "#{context}_#{key}" | |
if value.respond_to? :key | |
flatten_hash(value, flattened_key, new_hash) | |
else | |
new_hash[flattened_key]=value | |
end | |
end | |
new_hash | |
end | |
structure = { "one" => "a", "two" => {'three' => 'b', 'four' => 'c'}} | |
# should yield {"one"=>"a", "two_three"=>"b", "two_four"=>"c"} | |
puts flatten_hash(structure) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment