krunal shah krunal shah - 8 months ago 82
Ruby Question

Insert rows on specific line in a file

I have opened my existing file in r+ mode.

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


I want to insert some other rows at specific line no..
Like i want insert "Hii " on line number 10.
"hello " on line number 2.
"world " on line number 20.

How may i handle it in ruby ??

Answer Source

This has worked for me in the past:

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
    pos = f.pos                     # save your position in the file
    rest =                   # save the rest of the file pos                      # go back to the old position
    f.write sdat                    # write new data
    f.write rest                    # write rest of file
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download