Skipping the First Line when reading in a text file

I’m using ruby’s File to open and read in a text file inside of a rake
task. Is there a setting where I can specify that I want the first line
of
the file skipped?

Here’s my code so far:

desc “Import users.”
task :import_users => :environment do
File.open(“users.txt”, “r”, ‘\r’).each do |line|
id, name, age, email = line.strip.split(’,’)
u = User.new(:id => id, :name => name, :age => age, :email =>
email)
u.save
end
end

Thanks,

Andrew

This is by no means a RoR question. But the solution is pretty simple,
so
I’ll give in.

One way to do it would be to just put “next if line.lineno == 1” at the
beginning of the loop.

On Jan 26, 2012, at 8:18 PM, Bala TS wrote:

reader.each{|row|
first_field = row[0]
second_field = row[1]

Module_Name.create(
:attribute1 => first_field,
:attribute2 => second_field
)
}

I don’t know if CSV has the option, but FasterCSV has an option you can
pass to inform it that the first line is the header row and it will skip
it automatically…

I am using csv…

it is work:

if you are interested try this way:

require ‘csv’

reader = CSV.open(“file_location”, “r”)
reader.shift # this line is used to skip the first header line
reader.each{|row|
first_field = row[0]
second_field = row[1]

ModuleName.create(
:attribute1 => first_field,
:attribute2 => second_field
)
}

Bye:)
bdeveloper01

Hai!

That is depending upon gem. if you use csv then follow about steps and
if you use fastercsv then follows this link

http://fastercsv.rubyforge.org/

Bye:)
bdeveloper01