Skip to content

Instantly share code, notes, and snippets.

@jofi
Created June 7, 2012 08:21
Show Gist options
  • Save jofi/2887383 to your computer and use it in GitHub Desktop.
Save jofi/2887383 to your computer and use it in GitHub Desktop.
CSV manipulation in ruby
require 'csv'
# http://ruby-doc.org/stdlib-1.9.2/libdoc/csv/rdoc/CSV.html
# READING !!!FROM FILE!!!!
# Line by Line:
CSV.foreach('csvfile.csv') do
|row|
puts row #array
end
# All at once:
array_of_arrays = CSV.read('csvfile.csv')
# READING !!!FROM STRING!!!!!
# Line by line:
str = File.read('csvfile.csv')
CSV.parse(str) do
|row|
puts row #array
end
# All at once:
array_of_arrays = CSV.parse(str)
# WRITING
# To a file
CSV.open("csvfile_out.csv", "wb", col_sep: ";") do |csv|
csv << ["row", "of", "CSV", "data"]
csv << ["another", "row"]
# ...
end
# To a string
str = CSV.generate do |csv|
csv << ["row", "of", "CSV", "data"]
csv << ["another", "row"]
# ...
end
puts str
# OPTIONS (defaults):
# :col_sep
# ","
#
# :row_sep
# :auto
#
# :quote_char
# '"'
#
# :field_size_limit
# nil
#
# :converters
# nil
#
# :unconverted_fields
# nil
#
# :headers
# false
#
# :return_headers
# false
#
# :header_converters
# nil
#
# :skip_blanks
# false
#
# :force_quotes
# false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment