meW
meW

Reputation: 3967

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

Upvotes: 1

Views: 53

Answers (2)

Tom Lord
Tom Lord

Reputation: 28305

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

Upvotes: 1

Stefan
Stefan

Reputation: 114178

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.

Upvotes: 2

Related Questions