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


/ Published in: Ruby
Save to your folder(s)

Shows how to read/write fully formatted CSV with Ruby


Copy this code and paste it in your HTML
  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


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.