Archive for the ‘csv’ tag
Ruby: Ignore header line when parsing CSV file
As my Ruby journey continues one of the things I wanted to do today was parse a CSV file.
This article proved to be very useful for teaching the basics but it didn’t say how to ignore the header line that the CSV file contained.
The CSV file I was parsing was similar to this:
name, surname, location Mark, Needham, Sydney David, Smith, London
I wanted to get the names of people originally to use them in my code. This was the first attempt:
1 2 3 4 5 6 7 8 9 10 | require 'csv' def parse_csv_file_for_names(path_to_csv) names = [] csv_contents = CSV.read(path_to_csv) csv_contents.each do |row| names << row[0] end return names end |
I then printed out the names to see what was going on:
1 2 3 4 | names = parse_csv_file_for_names( "csv_file.csv" ) names.each do |name| puts name end |
This is what was printed:
name Mark David
It turns out that the ‘shift’ method is what I was looking for to help me ignore the first line of the file. The new and improved method now looks like this:
1 2 3 4 5 6 7 8 9 10 11 | require 'csv' 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 |
Not a particularly complicated thing to do in the end although I had been expecting to find a method on CSV that would allow me to ignore the header line automatically. As far as I could tell there isn’t one!