【发布时间】:2012-11-04 04:50:35
【问题描述】:
我有一个路径名为file 的文本文件,以及一些我想附加到它的内容string。我想做一些接近的事情
File.open(file, "a"){|io| io.puts(string)}
但是如果文件的原始内容没有以结束符$/结尾,我想在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
【讨论】:
r+ 模式。
File.open(file, "a"){ |io|
io.puts
io.puts(string)
}
【讨论】: