簡體   English   中英

閱讀ruby中的文本文件行

[英]reading text file lines in ruby

我想掃描文本文件中的每一行,除了第一行。

我通常會這樣做:

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

但是line = file.gets從第一行開始讀取line = file.gets行。

我如何從第二行開始閱讀?

為什么不簡單地調用file.gets並丟棄結果:

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

我會以一種簡單的方式做到這一點:

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

你真的想避免閱讀第一行或避免使用它。 如果您正在讀取該行但是您想避免處理它,那么您可以使用lineno在處理期間忽略該行,如下所示

f = File.new "/tmp/xx"

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM