Mohamed El Mahallawy Mohamed El Mahallawy - 4 months ago 16
Ruby Question

How to add CSV headers

I need to add a new column and header to the CSV file that I want to do some calculations to:

@csv = CSV.read(filename, headers: true, skip_blanks: true, encoding:'windows-1251:utf-8')


I want to an additional header called "New_header" and go row by row where New_header is the addition of
column 1 + column 2
.

How can I do this?

Answer

Simply add the column you want to each line - it will be added as a new column at the end:

@csv.each { |line| line['New_header'] = line[0].to_i + line[1].to_i }

Example:

@csv = CSV.parse("column1,column2,column3\n1,2,three\n2,4,six", headers: true)
@csv.each { |line| line['New_header'] = line[0].to_i + line[1].to_i }

puts @csv.to_csv
# => column1,column2,column3,New_header
#    1,2,three,3
#    2,4,six,6