2014-11-06 47 views
0

在本練習中,我完全編寫了所有代碼,甚至通過字面複製和粘貼本書中的代碼(Learn Ruby the Hard Way)進行雙重檢查。由於某種原因,當我調用print_a_line()函數時,它將不會打印出我經歷的current_line參數,直到第3次調用它將在行前打印出3。有沒有在這裏錯過的IO流的一些沖洗或與Powershell的一些細微差別?LRTHW練習20奇怪的輸出

我在Windows 8 64位機器上運行Ruby 2.0.0p576(x64)。

代碼:

input_file = ARGV.first 

def print_all(f) 
    puts f.read 
end 

def rewind(f) 
    f.seek(0) 
end 

def print_a_line(line_count, f) 
    puts "#{line_count}, #{f.gets.chomp}" 
end 

current_file = open(input_file) 

puts "First let's print the whole file:\n" 

print_all(current_file) 

puts "Now let's rewind, kind of like a tape." 

rewind(current_file) 

puts "Let's print three lines:" 

current_line = 1 
print_a_line(current_line, current_file) 

current_line = current_line + 1 
print_a_line(current_line, current_file) 

current_line = current_line + 1 
print_a_line(current_line, current_file) 
+0

你的輸出是什麼樣的? – tadman 2014-11-06 17:29:39

+0

除了打印出行號之外,它具有一切正確性。 EX: ',這是第1行.' ',這是第2行.' '3,這是行3.' – LSavage 2014-11-06 18:01:37

+0

這對我很有用,所以我不確定你在看什麼或爲什麼這是故障。你是否正在運行這個代碼?你是用'ruby'還是'irb'運行它? – tadman 2014-11-06 18:06:38

回答

1

我刪除test.txt文件,並從頭開始重建它,這完全使代碼工作。我不是100%的原因,但我有一種預感,那就是在許多不同的測試中重複使用該文件,並在PowerShell中玩耍時,我無意中在文件中留下了一些奇怪的格式,導致其行爲不同。

+0

有可能是在那裏有一些瘋狂的東西,當輸出時,會導致終端畫自己。 – tadman 2014-11-07 19:56:15