Is it possible to change the default field separator from comma to to some other character, e.g '|'
for exporting?
Asked
Active
Viewed 7.0k times
3 Answers
130
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

Dylan Markow
- 123,080
- 26
- 284
- 201
5
CSV::Writer
has a generate method, which accepts a separator string as argument.
#!/usr/bin/env ruby
# +++ ruby 1.8 version +++
require "csv"
outfile = File.open('csvout', 'wb')
CSV::Writer.generate(outfile, '|') do |csv|
csv << ['c1', nil, '', '"', "\r\n", 'c2']
end
outfile.close

miku
- 181,842
- 47
- 306
- 310
-
3This only works in Ruby 1.8, in 1.9 they got rid of the Writer class. – Dylan Markow Jan 27 '11 at 21:17