简体   繁体   中英

Ruby - Reading a file causes an extra line while printing

How can I avoid a new line when I use 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 )

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.

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):

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

To delete only the trailing whitespaces, you can use String#rstrip :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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