Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map and edit a CSV file with Ruby

Tags:

ruby

csv

Is there a way to edit a CSV file using the map method in Ruby? I know I can open a file using:

CSV.open("file.csv", "a+")

and add content to it, but I have to edit some specific lines.

The foreach method is only useful to read a file (correct me if I'm wrong).

I checked the Ruby CSV documentation but I can't find any useful info.

My CSV file has less than 1500 lines so I don't mind reading all the lines.

like image 731
Badr Tazi Avatar asked Oct 24 '15 18:10

Badr Tazi


People also ask

What does CSV parse Do Ruby?

The parser works in the Encoding of the IO or String object being read from or written to. Your data is never transcoded (unless you ask Ruby to transcode it for you) and will literally be parsed in the Encoding it is in. Thus CSV will return Arrays or Rows of Strings in the Encoding of your data.


1 Answers

Another answer using each.with_index():

rows_array = CSV.read('sample.csv')

desired_indices = [3, 4, 5].sort # these are rows you would like to modify
rows_array.each.with_index(desired_indices[0]) do |row, index| 
  if desired_indices.include?(index)

    # modify over here
    rows_array[index][target_column] = 'modification'

  end
end

# now update the file
CSV.open('sample3.csv', 'wb') { |csv| rows_array.each{|row| csv << row}}

You can also use each_with_index {} insead of each.with_index {}

like image 109
illusionist Avatar answered Sep 27 '22 23:09

illusionist