Skip to content

Instantly share code, notes, and snippets.

@JasonTrue
Last active September 28, 2015 20:07
Show Gist options
  • Save JasonTrue/f6ef2350d08ab349dc76 to your computer and use it in GitHub Desktop.
Save JasonTrue/f6ef2350d08ab349dc76 to your computer and use it in GitHub Desktop.
Flatten a hash structure
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