在本練習中,我完全編寫了所有代碼,甚至通過字面複製和粘貼本書中的代碼(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)
你的輸出是什麼樣的? – tadman 2014-11-06 17:29:39
除了打印出行號之外,它具有一切正確性。 EX: ',這是第1行.' ',這是第2行.' '3,這是行3.' – LSavage 2014-11-06 18:01:37
這對我很有用,所以我不確定你在看什麼或爲什麼這是故障。你是否正在運行這個代碼?你是用'ruby'還是'irb'運行它? – tadman 2014-11-06 18:06:38