I am trying to import data into rails (3.1) and I have created this rake task to parse a tab delimited text file (generated by Excel on Mac), the file has standard Mac OS X line endings.
desc "Import users."
task :import_users => :environment do
File.open("users.txt", "r", '\r').each do |line|
id, name, age, email = line.strip.split('/t')
u = User.new(:id => id, :name => name, :age => age, :email => email)
u.save
end
end
However, when I try to run this rake task I get the following error:
rake aborted!
can't convert String into Integer
My guess is that Ruby doesn't like converting the Age heading into a numerical age variable in my User class. Is there a way I can either (a) skip the header line in the file OR (b) do this cast on the fly in Ruby?
Note: This is one of many attempts to read in some data to Ruby. Whenever I tried to read in the data before, I never seemed to get this error. The string value always got casted to 0.0.
Simpliest solution, which come to mind was:
Of course, you will still have an error on a first line of a file, if you got your headers there.