2 Replies - 2133 Views - Last Post: 16 February 2011 - 02:34 PM Rate Topic: -----

#1 Sergio Tapia  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1253
  • View blog
  • Posts: 4,168
  • Joined: 27-January 10

Error when trying to parse a CSV file.

Posted 16 February 2011 - 10:44 AM

require 'csv'

class Car
  
  attr_accessor :year, :make, :model, :length
  
  def initialize(year, make, model, length)
    @year = year
    @make = make
    @model = model
    @length = Float(length)
  end
  
  def to_s
    "The #{@make} #{@model} was built in #{@year} and measured #{@length}."
  end
end

class CsvReader
  attr_accessor :cars
  def initialize
    @cars_in_file = []
  end
  
  def read_in_csv_data(csv_file_name)
    CSV.foreach(csv_file_name, headers: true) do |row|
      @cars_in_file << Car.new(row["Year"], row["Make"], row["Model"], row["Length"])
    end
  end
end

reader = CsvReader.new
reader.read_in_csv_data("/home/stapiagutierrez/Desktop/Pickaxe/cars.csv")


puts reader.cars[0]


The error is fired in the CsvReader class, in the CSV.foreach area. Here is the error:

Quote

CsvReader.rb:26: syntax error, unexpected ':', expecting ')'
CSV.foreach(csv_file_name, headers: true) do |row|
^
CsvReader.rb:30: syntax error, unexpected kEND, expecting $end


Any suggestions on how to fix this? Thanks!

Is This A Good Question/Topic? 0
  • +

Replies To: Error when trying to parse a CSV file.

#2 5thWall  Icon User is offline

  • Occasional Member

Reputation: 31
  • View blog
  • Posts: 530
  • Joined: 17-September 08

Re: Error when trying to parse a CSV file.

Posted 16 February 2011 - 12:35 PM

The headers: true isn't valid ruby. According to the doc the foreach method takes a path to the file, and a hash of options. The hash should probably look something like this { :headers => true }.

Hashes in ruby follow the { key => value, key => value } syntax. Where the key is usually a symbol or a string (though I believe it can be any object).

This post has been edited by 5thWall: 16 February 2011 - 12:36 PM

Was This Post Helpful? 0
  • +
  • -

#3 Sergio Tapia  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1253
  • View blog
  • Posts: 4,168
  • Joined: 27-January 10

Re: Error when trying to parse a CSV file.

Posted 16 February 2011 - 02:34 PM

Thank you for your help. :)

This is what I came up with:
http://www.dreaminco...&showentry=3221
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1