Posted By

m1b on 08/19/11


Tagged

ruby csv


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

Priestd09


Ruby CSV writing and reading example with quotes, line breaks and commas in the fields


 / Published in: Ruby
 

Shows how to read/write fully formatted CSV with Ruby

  1. #require 'csv'
  2. require 'rubygems'
  3. require 'fastercsv'
  4.  
  5. FCSV { |out|
  6. out << [:Number,:One,:Two,:Three,:Four]
  7. out << [1,"first","second","Third one quoted with a, comma","fourth \"double quotes\"\n line break"]
  8. out << [2,"erst","zweite","Dritte,mit Komma","viertl"]
  9. out << [3,"primero","segundo","tercero","cuarto,con la coma"]
  10. }
  11.  
  12. FasterCSV.foreach("sample.csv", {:headers=>true}) { |r|
  13.  
  14. puts "#{r.length} fields: >>#{r.inspect}<<"
  15. r.each { |header, value|
  16. puts "\t#{header}=#{value}"
  17. }
  18. }

Report this snippet  

You need to login to post a comment.