2011-10-24 48 views
2

我不知道我怎麼能確定當我在我在讀取文件的最後一行。我的代碼看起來像確定最後一行在Ruby中

File.open(file_name).each do |line| 
    if(someway_to_determine_last_line) 
end 

我注意到,有一個文件。 EOF?方法,但如何在讀取文件時調用該方法?謝謝!

+0

的東西,一堆是怎麼回事。我需要知道我所在的行是文件的最後一行還是最後一行非空行。 –

回答

6

如果你用迭代的each文件,那麼最後一行將被的檔案結尾之後傳遞到塊達到,因爲最後一行是,根據定義,符合EOF結束。

所以只需在塊中調用file.eof?

如果您想確定文件中是否爲最後的非空行,您必須實施某種預讀。

3

根據您需要這方面的「最後一個非空行」做什麼,你也許能夠做這樣的事情:

last_line = nil 
File.open(file_name).each do |line| 
    last_line = line if(!line.chomp.empty?) 
    # Do all sorts of other things 
end 
if(last_line) 
    # Do things with the last non-empty line. 
end 
1

fd.eof?作品,但只是爲了好玩,這裏有一個通用的解決方案這適用於任何類型的統計員(Ruby 1.9的)的:

class Enumerator 
    def +(other) 
    Enumerator.new do |yielder| 
     each { |e| yielder << e } 
     other.each { |e| yielder << e } 
    end 
    end 

    def with_last 
    Enumerator.new do |yielder| 
     (self + [:some_flag_here]).each_cons(2) do |a, b| 
     yielder << [a, b == :some_flag_here] 
     end 
    end 
    end 
end 

# a.txt is a file containing "1\n2\n3\n" 
open("a.txt").lines.with_last.each do |line, is_last| 
    p [line, is_last] 
end 

,輸出:

["1\n", false] 
["2\n", false] 
["3\n", true] 
0

打開你的文件,並使用readline方法:

爲了簡單地操縱文件的最後一行進行以下步驟:

f = File.open('example.txt').readlines 
f.each do |readline| 
    if readline[f.last] 
    puts "LAST LINE, do something to it" 
    else 
    puts "#{readline} " 
    end 
end 

1行中讀出該文件作爲線

行2所使用的陣列該對象並遍歷他們每個人

3次線測試,如果當前行中的最後一行匹配

4號線的行爲,如果它是一個匹配

5號線& 6不匹配的情況下手柄的行爲

0

祕訣是.to_a

lines = File.open(filename).to_a 

獲取的第一行:

puts lines.first 

獲取最後一行:

puts lines.last 

獲取ñ行的文件:

puts lines.at(5) 

獲取的行數:

puts lines.count 
相關問題