Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我有一个带有路径名的文本文件file,以及一些string我想附加到它的内容。我想做一些接近
file
string
File.open(file, "a"){|io| io.puts(string)}
但如果文件的原始内容不以结束行字符结束$/,我想在前面插入一个string。最有效的方法是什么?
$/
File.open(file, 'r+') do |f| unless (last = f.readlines[-1]) && last.end_with?($/) f.puts $/ end f.puts string end
File.open(file, "a"){ |io| io.puts io.puts(string) }