![](/img/trans.png)
[英]Moving to the last line of a file while reading it in a .each loop in Ruby
[英]Ruby - Reading a file causes an extra line while printing
当我使用puts line + "test"
时如何避免换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
有什么办法阻止它产生多余的线路吗?
如果要删除换行符,请使用String#chomp进行处理。
http://apidock.com/ruby/v1_9_3_392/String/chomp
puts line.chomp + "test"
使用String#strip去除所有前导和尾随空格字符(包括换行符):
puts line.strip + "test"
# => line1test
要只删除结尾的空格,可以使用String#rstrip :
puts line.rstrip + "test"
# => line1test
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.