Alex Rivera | Logout

How can I skip the header row when reading a CSV in Ruby?

Asked 2012-07-31T12:47:59.327
31

Ruby's CSV class makes it pretty easy to iterate over each row:

CSV.foreach(file) { |row| puts row }

However, this always includes the header row, so I'll get as output:

header1, header2
foo, bar
baz, yak

I don't want the headers though. Now, when I call …

CSV.foreach(file, :headers => true)

I get this result:

#<CSV::Row:0x10112e510
    @header_row = false,
    attr_reader :row = [
        [0] [
            [0] "header1",
            [1] "foo"
        ],
        [1] [
            [0] "header2",
            [1] "bar"
        ]
    ]
>

Of course, because the documentation says:

This setting causes #shift to return rows as CSV::Row objects instead of Arrays

But, how can I skip the header row, returning the row as a simple array? I don't want the complicated CSV::Row object to be returned.

I definitely don't want to do this:

first = true
CSV.foreach(file) do |row|
  if first
    puts row
    first = false
  else
    # code for other rows
  end
end
Edit
Report

1 Answer

16

Look at #shift from CSV Class:

The primary read method for wrapped Strings and IOs, a single row is pulled from the data source, parsed and returned as an Array of fields (if header rows are not used)

An Example:

require 'csv'

# CSV FILE
# name, surname, location
# Mark, Needham, Sydney
# David, Smith, London

def parse_csv_file_for_names(path_to_csv)
  names = []  
  csv_contents = CSV.read(path_to_csv)
  csv_contents.shift
  csv_contents.each do |row|
    names << row[0]
  end
  return names
end
answered 2012-07-31T12:57:04.220

Your Answer