KnightKing
KnightKing

Reputation: 21

Ruby CSV File Parsing, Headers won't format?

My rb file reads:

require "csv"
puts "Program1 initialized."

contents = CSV.open "data.csv", headers: true
contents.each do |row|
  name = row[4]
  puts name
end

...but when i run it in ruby it wont load the program. it gives me the error message about the headers:

syntax error, unexpected ':', expecting $end
contents = CSV.open "data.csv", headers: true

so I'm trying to figure out, why won't ruby let me parse this file? I've tried using other csv files I have and it won't load, and gives me an error message. I'm trying just to get the beginning of the program going! I feel like it has to do with the headers. I've updated as much as I can, mind you I'm using ruby 1.8.7. I read somewhere else that I could try to run the program in irb but it didn't seem like it needed it. so yeah... thank you in advance!!!!

Upvotes: 2

Views: 857

Answers (1)

Sam
Sam

Reputation: 894

Since you are using this with Ruby 1.8.7, :headers => true won't work in this way. The simplest way to ignore the headers and get your data is to shift the first row in the data, which would be the headers:

require 'csv'
contents = CSV.open("data.csv", 'r')
contents.shift

contents.each do |row|
  name = row[4]
  puts name
end

If you do want to use the syntax with headers in ruby 1.8, you would need to use FasterCSV, something similar to this:

require 'fastercsv'

FasterCSV.foreach("data.csv", :headers => true) do |fcsv_obj|
puts fcsv_obj['name']
end

(Refer this question for further read: Parse CSV file with header fields as attributes for each row)

Upvotes: 3

Related Questions