简体   繁体   中英

reading text file lines in ruby

I would like to scan each line in a text file, EXCEPT the first line.

I would usually do:

while line = file.gets do
...
...etc
end

but line = file.gets reads EVERY single line starting from the first.

How do I read from the second line onwards?

Why not simply call file.gets once and discard the result:

file.gets
while line = file.gets
    # code here
end

I would do it in a simple fashion:

IO.readlines('filename').drop(1).each do |line| # drop the first array element
  # do any proc here
end

Do you actually want to avoid reading the first line or avoid doing something with it. If you are OK reading the line but you want to avoid processing it then you can use lineno to ignore the line during processing as follows

f = File.new "/tmp/xx"

while line = f.gets do
  puts line unless f.lineno == 1
end

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