简体   繁体   English

Ruby - 在新行中追加数据而不引入空行

[英]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.我在fd.txt中已经有一行,当我插入三个多行时,第一行紧跟在现有数据之后。 Here's an example:这是一个例子:

fd.txt 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:我得到以下 output:

This is past data.Line 1
Line 2
Line 3

But, I need Line 1 from the second line.但是,我需要第二Line 1的第一行。 So I add "\n" in file.puts "\nLine 1" but this adds an additional empty line right before Line 1 .所以我在file.puts "\nLine 1"中添加了"\n" ,但这会在Line 1之前添加一个额外的空行。 What update should I make to my code to get the following output:我应该对我的代码进行什么更新以获得以下 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)不是很优雅,但是您可以检查最后一个字符是否为\n并添加一个:(我假设您不知道文件是否以换行符结尾)

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

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

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