Skip to content

Instantly share code, notes, and snippets.

@abhishek77in
Created August 8, 2014 19:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save abhishek77in/2ae4a061000418e04cf9 to your computer and use it in GitHub Desktop.
Save abhishek77in/2ae4a061000418e04cf9 to your computer and use it in GitHub Desktop.
Flatten ruby hash, Could be used to convert nested ruby hash (or json) to csv
def flatten_hash(hash, results = {}, parent_key = '')
return results unless hash.kind_of?(Hash)
hash.keys.each do |key|
# current_key = "#{parent_key}[#{key}]" # uncomment this if you want to keep parent key as a partof key for flattened hash (csv column name)
current_key = key
if hash[key].kind_of?(Hash)
results = flatten_hash(hash[key], results, current_key)
else
if hash[key].kind_of?(Array)
results[current_key] = hash[key].reject(&:empty?).join("; ")
else
results[current_key] = hash[key]
end
end
end
results
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment