How to write columns header to a csv file with Ruby?

前端 未结 3 673
Happy的楠姐
Happy的楠姐 2020-12-14 07:33

I am having trouble writing columns to a csv file with Ruby. Below is my snippet of code.

 calc = numerator/denominator.to_f
 data_out = \"#{numerator}, #{de         


        
3条回答
  •  渐次进展
    2020-12-14 08:05

    Best way to handle csv file is to use Ruby's CSV module.

    I had same problem after reading CSV code I came across this solution which i find most efficient.

    headers = ['col1','col2','col3']
    
    CSV.open(file_path, 'a+', {force_quotes: true}) do |csv|
      csv << headers if csv.count.eql? 0 # csv.count method gives number of lines in file if zero insert headers
    end
    

提交回复
热议问题