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

前端 未结 3 671
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:00

    I would recommend to use the CSV-library instead:

    require 'csv'
    
    CSV.open('test.csv','w', 
        :write_headers=> true,
        :headers => ["numerator","denominator","calculation"] #< column header
      ) do|hdr|
      1.upto(12){|numerator|
        1.upto(12){ |denominator|
          data_out = [numerator, denominator, numerator/denominator.to_f]
          hdr << data_out
        }
      }
    end
    

    If you can't use the w option and you really need the a+ (e.g., the data isn't available all at once), then you could try the following trick:

    require 'csv'
    
    column_header = ["numerator","denominator","calculation"]
    1.upto(12){|numerator|
      1.upto(12){ |denominator|
        CSV.open('test.csv','a+', 
            :write_headers=> true,
            :headers => column_header
          ) do|hdr|
              column_header = nil #No header after first insertion
              data_out = [numerator, denominator, numerator/denominator.to_f]
              hdr << data_out
            end
      }
    }
    

提交回复
热议问题