Changing field separator/delimiter in exported CSV using Ruby CSV

前端 未结 3 1755
长发绾君心
长发绾君心 2020-12-14 14:19

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

3条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-14 15:11

    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

提交回复
热议问题