views:

60

answers:

1

I have a CSV file formatted just like this:

name,color,tasty,qty
apple,red,true,3
orange,orange,false,4
pear,greenish-yellowish,true,1

As you can see, each column in the Ruby OO world represents a mix of types -- string, string, boolean, int.

Now, ultimately, I want to parse each line in the file, determine the appropriate type, and insert that row into a database via a Rails migration. For ex:

Fruit.create(:name => 'apple', :color => 'red', :tasty => true, :qty => 3)

Help!

+1  A: 

For Ruby 1.8:

require 'fastercsv'

FasterCSV.parse(my_string, :headers => true) do |row|
  Fruit.create!(
    :name => row['name'],
    :color => row['color'],
    :tasty => row['tasty'] == 'true',
    :qty => row['qty].to_i
  )
end

For Ruby 1.9, just rename FasterCSV to CSV and fastercsv to csv:

require 'csv'

CSV.parse(my_string, :headers => true) do |row|
  # same as ruby-1.8
end
Justice
FasterCVS is a gem so you may have to install and don't forget to `require 'fastercvs'`
Tony Fontenot
I'm getting this error: "Please switch to Ruby 1.9's standard CSV library. It's FasterCSV plus support for Ruby 1.9's m17n encoding engine."Any idea how to handle?
keruilin
I updated the answer.
Justice