1

I've got this bit of code:

presorted_csv = CSV.read 'out.csv'
presorted_csv.sort! { |a, b| a[0].to_i <=> b[0].to_i }

I'm now wanting to simply write the sorted CSV file to disk. I'd expect it to be something like:

CSV.write('new.csv', presorted_csv)

however while there's a read method:

http://ruby-doc.org/stdlib-2.0.0/libdoc/csv/rdoc/CSV.html#method-c-read

there's no write method!

How do I do this in 1 line of code?

Snowcrash
  • 80,579
  • 89
  • 266
  • 376
  • There is. http://ruby-doc.org/stdlib-2.0.0/libdoc/csv/rdoc/CSV.html#class-CSV-label-To+a+File - open the file and write – kiddorails Sep 28 '17 at 19:02
  • 1
    No, that opens the file and gives you a handle to write rows to the file. I've already got a handle. I simply want to write to the file in 1 line. – Snowcrash Sep 28 '17 at 19:08
  • Possible duplicate of [How do I create a new CSV file in Ruby?](https://stackoverflow.com/questions/12718872/how-do-i-create-a-new-csv-file-in-ruby) – ulferts Sep 28 '17 at 19:14
  • Tip: `sort_by! { |v| v[0].to_i }` would be more succinct. – tadman Sep 28 '17 at 19:23
  • Please edit to show the value of `presorted_csv` (pared down if necessary, but complete). Those giving answers can then use that information to show calculations. – Cary Swoveland Sep 28 '17 at 22:00
  • @CarySwoveland is that really necessary?! The line of code `presorted_csv = CSV.read 'out.csv'` should be sufficient. It's a simple CSV file like: 'a,b,c,d'. – Snowcrash Sep 29 '17 at 11:55

0 Answers0