Ruby - 在打印时读取文件会导致额外的行

时间:2015-10-13 04:02:51

标签: ruby file

当我使用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

无论如何阻止它产生额外的线?

2 个答案:

答案 0 :(得分:3)

如果要删除换行符,请使用String#chomp来处理它。

http://apidock.com/ruby/v1_9_3_392/String/chomp

puts line.chomp + "test"

答案 1 :(得分:0)

使用String#strip删除所有前导尾随空白字符(包括新行):

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

要仅删除尾随空格,您可以使用String#rstrip

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