How to parse CSV data with Ruby

Ruby alternatives for parsing CSV files

  • Ruby String#split (slow)
  • Built-in CSV (ok, recommended)
  • ccsv (fast & recommended if you have control over CSV format)
  • CSVScan (fast & recommended if you have control over CSV format)
  • Excelsior (fast & recommended if you have control over CSV format)

CSV library benchmarks can be found here and here

Parsing with plain Ruby

filename = 'data.csv'
file = File.new(filename, 'r')

file.each_line("\n") do |row|
  columns = row.split(",")
  
  break if file.lineno > 10
end

This option has several problems…

Parsing with the built-in CSV library

require 'csv'

CSV.open('data.csv', 'r', ';') do |row|
  puts row
end

require 'csv'

CSV.foreach("changes.csv", quote_char: '"', col_sep: ';', row_sep: :auto, headers: true) do |row|
  puts row[0]
  puts row['xxx']
end

Parsing with the ccsv library

ccsv is hosted on GitHub.

require 'rubygems'
require 'ccsv'

Ccsv.foreach(file) do |values|
  puts values[0]
end

Parsing with the CSVScan library

CSVScan can be downloaded from here.

require "csvscan"

open("data.csv") do |io|
  CSVScan.scan(io)  do|row|
    puts row
  end
end

Updated 2258 days ago
{"cc_re__cc_re__cc_by_3_0": [") {\n  var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;\n  dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';\n  (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);\n})();\n*/</script></div></div><div class=\"columns sixteen\" id=\"footer\"><ul class=\"no-style\"><li><a href=\"http://aktagon.com\" id=\"built-by\" title=\"We help you build better web and mobile apps\">Aktagon</a></li><li class=\"sep\">|</li><li><a href=\"http://creativecommons.org/licenses/by/3.0/\" rel=\"license\">Creative Commons Attribution 3.0 License</a></li><li class=\"sep\">|</li><li><a href=\"/about\">About this site</a></li></ul></div></div><script type=\"text/javascript\">(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){\n(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),\nm=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)\n})(window,document,'script','//www.google-analytics.com/analytics.js','ga');\n\nga('create', 'UA-40306"]}