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
  • What was the standard 7 years ago? Commented Mar 8, 2017 at 11:46

1 Answer 1

5

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
Sign up to request clarification or add additional context in comments.

3 Comments

FasterCVS is a gem so you may have to install and don't forget to require 'fastercvs'
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?
FasterCSV is now part of Ruby as its default CSV class so just use require 'csv' and you'll be good to go.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.