简体   繁体   中英

Data casting error when reading from a file in Ruby

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM