Filip Bartuzi
Filip Bartuzi

Reputation: 5931

Open CSV without reading header rows in Ruby

I'm opening CSV using Ruby:

CSV.foreach(file_name, "r+") do |row|
  next if row[0] == 'id'
  update_row! row    
end

and I don't really care about headers row.

I don't like next if row[1] == 'id' inside loop. Is there anyway to tell CSV to skip headers row and just iterate through rows with data ?

I assume provided CSVs always have a header row.

Upvotes: 1

Views: 5236

Answers (3)

Sculper
Sculper

Reputation: 756

There are a few ways you could handle this. The simplest method would be to pass the {headers: true} option to your loop:

CSV.foreach(file_name, headers: true) do |row|
  update_row! row    
end

Notice how there is no mode specified - this is because according to the documentation, CSV::foreach takes only the file and options hash as its arguments (as opposed to, say, CSV::open, which does allow one to specify mode.

Alternatively, you could read the data into an array (rather than using foreach), and shift the array before iterating over it:

 my_csv= CSV.read(filename)
 my_csv.shift
 my_csv.each do |row|
     update_row! row 
 end

Upvotes: 3

the Tin Man
the Tin Man

Reputation: 160621

A simple thing to do that works when reading files line-by-line is:

CSV.foreach(file_name, "r+") do |row|
  next if $. == 1
  update_row! row    
end

$. is a global variable in Ruby that contains the line-number of the file being read.

Upvotes: -1

Tim
Tim

Reputation: 2028

According to Ruby doc:

options = {:headers=>true}
CSV.foreach(file_name, options) ...

should suffice.

Upvotes: 1

Related Questions