如何避免新線的時候我用puts line + "test"
紅寶石 - 讀取文件導致額外的行打印時
示例代碼:
File.open("test.txt", "r") do |f|
f.each_line do |line|
puts line + "test" #=>line1\ntest
#puts "test" + line #=> testline1
end
end
當我使用:
puts "test" + line`
它顯示:
testline1
(line1
是在test.txt
唯一)
然而,
puts line + "test"
的樣子:
test
line1
反正從產生額外的行停止呢?
從文件讀取時,這是非常典型的。它將拾取該行的末尾(即新行)並將該行傳遞給該行。只需在最後加上'.chomp'來解析它。在你的情況:'puts line.chomp +'test'' –
不用打開文件,然後使用'each_line',使用'foreach'。它會簡化和減少你的代碼。 –