简体   繁体   English

Ruby-读取文件会导致打印时多出一行

[英]Ruby - Reading a file causes an extra line while printing

How can I avoid a new line when I use puts line + "test" 当我使用puts line + "test"时如何避免换puts line + "test"

Example code: 示例代码:

  File.open("test.txt", "r") do |f|
    f.each_line do |line|
      puts line + "test" #=>line1\ntest
      #puts "test" + line #=> testline1
    end
  end

When I use: 当我使用时:

puts "test" + line` 

It shows: 表明:

testline1

( line1 being the only thing in the test.txt ) line1test.txt的唯一内容)

However, 然而,

puts line + "test" 

looks like: 看起来像:

test
line1

Is there anyway of stopping it from producing the extra line? 有什么办法阻止它产生多余的线路吗?

If you want to strip out the newline, use String#chomp to take care of it. 如果要删除换行符,请使用String#chomp进行处理。

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

puts line.chomp + "test"

Use String#strip to strip out all the leading and trailing whitespace characters (including new line): 使用String#strip去除所有前导尾随空格字符(包括换行符):

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

To delete only the trailing whitespaces, you can use String#rstrip : 要只删除结尾的空格,可以使用String#rstrip

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM