简体   繁体   中英

Ruby - Appending data in a new line without introducing an empty line

I already have one line in fd.txt and when I'm inserting three multiple lines, the first line appends right after the existing data. Here's an example:

fd.txt

This is past data.

New data

Line 1
Line 2
Line 3

When I run the following code:

open('fd.txt', 'a+') { |file|
  file.puts "Line 1"
  file.puts "Line 2"
  file.puts "Line 3"
}

I get the following output:

This is past data.Line 1
Line 2
Line 3

But, I need Line 1 from the second line. So I add "\n" in file.puts "\nLine 1" but this adds an additional empty line right before Line 1 . What update should I make to my code to get the following output:

This is past data.
Line 1
Line 2
Line 3

Not very elegant, but you could check whether the last character is a \n and add one otherwise: (I assume that you don't know if the file ends with a newline)

open('fd.txt', 'a+') do |file|
  file.puts unless file.pread(1, file.size - 1) == "\n"

  file.puts "Line 1"
  file.puts "Line 2"
  file.puts "Line 3"
end

It would be better of course to not have a missing newline in the first place.

Similar to the other proposed answer, you could do:

open('fd.txt', 'a+') do |file|
  file.seek(-1, IO::SEEK_END)
  file.puts unless file.read == "\n"

  file.puts "Line 1"
  file.puts "Line 2"
  file.puts "Line 3"
end

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