Skip lines before header in CSV file

I tried searching, but could not find a question about my problem. Let's say I have a CSV file that looks something like this:

Metadata line 1
Metadata line 2
Metadata line 3
Metadata line 4
foo,bar,baz
apple,orange,banana
cashew,almond,walnut

The row foo,bar,bazis the header, and the next row is the corresponding data. When I write my ruby ​​code as follows:

CSV.foreach("filename.csv",:headers=>true) do |row|
  puts "#{row}"
end

It breaks clearly. What is the best way to skip the lines before the header? Currently, I think I can do something like:

Find the first row with commas and get line number
Extract that line as an array
Pass that array to :headers

But it seems cumbersome - if I know exactly what the title bar is, what is the best way to go to this line and ignore everything before? Is it possible? If this is a question that was asked before, I will happily devour these answers, maybe my search fu is just not good enough.

Thank you very much!

+4
3

CSV skip_lines. , , .

: skip_lines - , , . String, Regexp. noil no . match, ArgumentError .

+3

, , CSV.

, , - , !

require 'csv'

3.times { DATA.readline }

csv = CSV.new(DATA, headers: true, return_headers: false)
csv.read.each do |row|
  p row
end
# => #<CSV::Row "header1":"1" "header2":"2">
# => #<CSV::Row "header1":"3" "header2":"4">
# => #<CSV::Row "header1":"5" "header2":"6">
p csv.headers
# => ["header1", " header2"]

__END__
# I know
# there are 3 lines
# here, so I can skip them.
header1,header2
1,2
3,4
5,6
+1

- :

require 'csv'

while (header = DATA.readline) !~ /,.*,/
end
csv = CSV.new(DATA.read, headers: header)
csv.each do |row|
  p row
end
p csv.headers

__END__
Metadata line 1
Metadata line 2
Metadata line 3
Metadata line 4
foo,bar,baz
apple,orange,banana
cashew,almond,walnut

: (# here, so I can skip them.) . , . . /,.*,/, , .

: .

2: DATA - ruby, (, f File.open(filename){|f| ...}.

+1

All Articles