In this example we will have a look how to read / write data to CSV file. It is necessary to include CSV library require 'csv', and we can name our file as change_data.rb:

require 'csv'
headers = ['id','lastname','firstname','city']

output = CSV.open('example_changed.csv', 'w',**{:col_sep => ';'})
CSV.open('example.csv', 'r',**{:col_sep => ';'}) do |csv|
csv.each do |row|
if row[2] == ""
row[2] = "Alen"
output << row
else
output << row
end
end
end

Additionally, in CSV.open method as an option, we could also include force_quotes:true if it is necessary. The original example looks like:

id;lastname;firstname;city
1;Hujdur;;Antwerpen
2;Hujdur;Amina;Antwerpen

After running change_data.rb script, we have a filled in value “Alen” in newly created CSV file example_changed.csv:

id;lastname;firstname;city
1;Hujdur;Alen;Antwerpen
2;Hujdur;Amina;Antwerpen