How to delete entire line in csv file in ruby ​​1.9.2

I am creating an application that reads data from a CSV file and stores this data in a database. I csv file, which I get from a third party, consists of a header in the first line that needs to be deleted before inserting this data into the database. How can I delete the first row programmatically, and then push only the values ​​or data into the database. I am using ruby ​​version 1.9.2, so I do not need to use "fastcsv". I use the standard CSV library.

Please help me

+4
source share
2 answers

You can get all rows at once using:

arr_of_arrs = CSV.read("path/to/file.csv") 

And then you can use arr_of_arrs.drop(1) to remove the header. Or you can use arr_of_arrs.each_with_index to skip the first line (header), for example:

 arr_of_arrs.each_with_index do |e, i| next if i == 0 #process each row here end 
+5
source

when you do:

 CSV.open(filename, :headers => true) do |row| # it will use the first line as headers. now you can do: row['my_header_value'] end 
+8
source

Source: https://habr.com/ru/post/1413674/


All Articles