Reputation: 42
I am trying to sort a CSV file.
I read the data from the file and store it into a hash:
somecsv = 'somecsv.csv'
CSV_Hash = {}
CSV.foreach(somecsv) do |col1, col2, col3|
CSV_Hash[col1] = col2, col3
end
I then do some sorting and want to write the data back into a CSV file:
CSV.open('somecsv2.csv', "wb") do |csv|
CSV_Hash.each do |row|
csv << row
end
end
The sample data is:
Filename REG1 REG2
zFile.exe A E
bFile.exe B F
aFile.exe C G
My expected output is:
Filename REG1 REG2
aFile.exe C G
bFile.exe B F
zFile.exe A E
The actual output is:
Filename ["REG1, REG2"]
aFile.exe ["C, G"]
bFile.exe ["B, F"]
zFile.exe ["A, E"]
My code works perfectly when I just had two columns, and I understand why it doesn't work for the third column. I just don't know where else to look to separate out the third column.
If this helps, this is what the hash looks like when output to the console:
{"Filename"=>["REG1", "REG2"], "aFile.exe"=>["C", "G"], "bFile.exe"=>["B", "F"], "zFile.exe"=>["A", "E"]}
Upvotes: 1
Views: 939
Reputation: 121010
CSV writer expects a flattened array, not the tuple string => array
:
- csv << row
+ csv << row.flatten
Hope it helps.
Upvotes: 2