Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete the entire row in the csv file in ruby 1.9.2

Tags:

ruby

csv

I am building an app which reads the data from the CSV file and stores those data into the database. I csv file which I get from the 3rd party consists of header in the first row which has to be deleted before pushing those data in to the database. How do I delete the first row pro grammatically and then push only the values or data to the database.I am using ruby 1.9.2 version, so I dont have to use "fastercsv". I am using the standard CSV library.

Kindly help me out

like image 205
Jeevan Dongre Avatar asked Dec 12 '22 02:12

Jeevan Dongre


2 Answers

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
like image 65
pguardiario Avatar answered Dec 31 '22 02:12

pguardiario


You can fetch all the rows at once by using:

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

And then you can use arr_of_arrs.drop(1) to remove header. Or you can use arr_of_arrs.each_with_index to skip the first row (header), like this:

arr_of_arrs.each_with_index do |e, i|
  next if i == 0

  #process each row here
end
like image 38
Hck Avatar answered Dec 31 '22 01:12

Hck