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

kru*_*hah 1 ruby ruby-on-rails file

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

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

结束

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

我怎么能在红宝石中处理它?

jde*_*eno 6

这在过去对我有用:

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
Run Code Online (Sandbox Code Playgroud)

  • 我不得不做一些修正:f.write sdat然后f.write rest.还需要确保sdat有一个新行(如果你想要一个). (2认同)