在文件中的特定行上插入行

我已经在r +模式下打开了现有文件。

open(“#{RAILS_ROOT} /locale/app.pot”,“r +”)do | f |

结束

我想在特定的行号中插入一些其他行。就像我想要在行号10上插入“Hii”。在行号20上的“hello”。行号20上的“世界”。

我怎么能在ruby中处理它?

这在过去对我有用:

def write_at(fname, at_line, sdat) open(fname, 'r+') do |f| while (at_line-=1) > 0 # read up to the line you want to write after f.readline end pos = f.pos # save your position in the file rest = f.read # save the rest of the file f.seek pos # go back to the old position f.write sdat # write new data f.write rest # write rest of file end end 

这可能不是最好的Ruby方式,但总的来说,在过去我必须这样做时,我会打开一个具有全局唯一名称的输出文件,并逐行读取和写入,保持行一路上计算。 (这不是维护世界上最伟大的事情,但实施起来非常简单)