Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing field separator/delimiter in exported CSV using Ruby CSV

Tags:

ruby

csv

Is it possible to change the default field separator from comma to to some other character, e.g '|' for exporting?

like image 734
Vincent Avatar asked Jan 27 '11 21:01

Vincent


2 Answers

Here's an example using a tab instead.

To a file:

CSV.open("myfile.csv", "w", {:col_sep => "\t"}) do |csv|   csv << ["row", "of", "CSV", "data"]   csv << ["another", "row"]   # ... end 

To a string:

csv_string = CSV.generate(:col_sep => "\t") do |csv|   csv << ["row", "of", "CSV", "data"]   csv << ["another", "row"]   # ... end 

Here's the current documentation on CSV: http://ruby-doc.org/stdlib/libdoc/csv/rdoc/index.html

like image 84
Dylan Markow Avatar answered Oct 27 '22 05:10

Dylan Markow


The previous CSV library was replaced with FasterCSV in Ruby 1.9.

require "csv"  output = CSV.read("test.csv").map do |row|   row.to_csv(:col_sep => "|") end puts output 
like image 34
Lri Avatar answered Oct 27 '22 04:10

Lri