Changing field separator/delimiter in exported CSV using Ruby CSV

RubyCsv

Ruby Problem Overview


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

Ruby Solutions


Solution 1 - Ruby

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

Solution 2 - Ruby

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

Solution 3 - Ruby

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionVincentView Question on Stackoverflow
Solution 1 - RubyDylan MarkowView Answer on Stackoverflow
Solution 2 - RubyLriView Answer on Stackoverflow
Solution 3 - RubymikuView Answer on Stackoverflow