Need to insert row in particular line in text file in ruby

hi All,

i have one text file with 100’s of lines and my scenarios is i need to insert a new line at row number 36 in text file… please help me how to do as am new to ruby script.

They are a few ways to do this but I would choose the simple way.

  1. Open the file and read all the data into a array.
  2. Insert the new line into the position of the array.
  3. Save the array to file with the original name.

Here’s the basic Ruby stuff to accomplish your request:

# datafile contents
# -----------------
# This is the first
# This is the second
# This is the fourth

print "Enter filename: "
filename = gets.chomp

ifile = File.new(filename)

data = ifile.readlines # read file contents into array - data

ifile.close

p data # display data array

data.insert(2, "This is the third\n") # insert new line into data array

p data # display data array

File.write(filename, data.join, mode: "w") # write(overwrite) data to original file

# datafile contents at the end
# -----------------
# This is the first
# This is the second
# This is the third
# This is the fourth