The Problem:
I have the following hash:
hash = {1=>{:price=>"400", :brand=>"Primark"}, 2=>{:price=>"1000", :brand=>"pull&bear"}, 3=>{:price=>"1700", :brand=>""}, 4=>{:price=>"500", :brand=>"H&M"}, 5=>{:price=>"500", :brand=>"Mango"}}
and I want to convert it into a csv file.
Approach so far:
My closest solution (inspired by) seems to overwrite itself constantly:
require 'csv'
(1..5).each do |id|
column_names = hash[id].keys
column_values = hash[id].values
s=CSV.generate do |csv|
csv << column_names
csv << column_values
end
File.write('the_file.csv', s)
end
Current csv file:
+---+------------+-------------+
| | A | B |
+---+------------+-------------+
| 1 | price,brand| |
| 2 | 500, Mango | |
+---+------------+-------------+
Desired csv output:
+---+------------+-------------+
| | A | B |
+---+------------+-------------+
| 1 | price | brand |
| 2 | 400 | Primark |
| 3 | 1000 | pull&bear |
| 4 | 1700 | |
| 5 | 500 | H&M |
| 6 | 500 | mango |
+---+------------+-------------+
There are several questions on here that either deal with the inverse (converting a csv into a nested hash) or only convert simple hashes into csv files, but not with nested hashes. I'm fairly new to Ruby and can't connect the dots here yet. Help would be greatly appreciated!