[英]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.