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

Viewed 30724

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
3 Answers
Related