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.
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.
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
thanks, can i have sample code…
But there is no line 36 …
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.
Sponsor our Newsletter | Privacy Policy | Terms of Service | Remote Ruby Jobs