[Ruby] Rubyでヘッダ付きのCSVを生成する
memo.
header = ["date", "name", "count"]
csv_data = CSV.generate("", :headers => header, :write_headers => true) do |csv|
csv << [Date.today, "data", 6]
end
追記:2018/01/17
中途半端な記述だったので追記。
例えばこんな形で。
require 'csv'
FILE_PATH = 'test.tsv'
HEADER = %w[date name count].freeze
OPTIONS = { col_sep: "\t", headers: HEADER, write_headers: true }.freeze
puts "\nStart...\n\n"
tsv_data = CSV.generate(OPTIONS) do |tsv|
tsv << [Date.today, 'foo', 6]
tsv << [Date.today - 1, 'bar', 2]
end
puts tsv_data
begin
File.open(FILE_PATH, 'w') do |file|
file.write(tsv_data)
end
rescue SystemCallError => e
puts %(class=[#{e.class}] message=[#{e.message}])
rescue IOError => e
puts %(class=[#{e.class}] message=[#{e.message}])
end
puts "\nComplete! See #{FILE_PATH}.\n"