Data casting error when reading from a file in Ruby

126 Views Asked by At

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.

1

There are 1 best solutions below

0
On BEST ANSWER

Simpliest solution, which come to mind was:

u = User.new(:id => id, :name => name, :age => Integer(age), :email => email)

Of course, you will still have an error on a first line of a file, if you got your headers there.