2015-10-13 84 views
-1

如何避免新線的時候我用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 

反正從產生額外的行停止呢?

+1

從文件讀取時,這是非常典型的。它將拾取該行的末尾(即新行)並將該行傳遞給該行。只需在最後加上'.chomp'來解析它。在你的情況:'puts line.chomp +'test'' –

+0

不用打開文件,然後使用'each_line',使用'foreach'。它會簡化和減少你的代碼。 –

回答

0

使用String#strip剝離所有的領先尾隨空白字符(包括新行):

puts line.strip + "test" 
# => line1test 

只刪除尾隨空格,你可以使用String#rstrip

puts line.rstrip + "test" 
# => line1test 
+1

雖然'strip'會去掉尾隨的空白區域,但它也會去掉主要的空白區域,這通常很重要。一個更好的選擇是'rstrip',它只能在字符串的末尾生效。 –