1

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"]}
3
  • How about an additional row.each do |data| Commented Jul 14, 2014 at 14:10
  • You don't say what OS you're on, but typically I'd sort a CSV file using the built-in sort command on Linux. Its -t (for field separator) and -k (for start/stop sort column) parameters make it possible to identify and sort on a particular column. You can tell it to use numeric sorting order if you want also. It's a LOT faster and can handle huge files. The only time I've run into problems is when a field contains the field-separator. Commented Jul 14, 2014 at 16:36
  • The OS is Windows 7, but thank you anyway. Commented Jul 15, 2014 at 8:39

1 Answer 1

2

CSV writer expects a flattened array, not the tuple string => array:

- csv << row
+ csv << row.flatten

Hope it helps.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.