1

Alright, so I have a ruby file and a text file. The code is like this:

fname = "sample.txt"
somefile = File.open(fname, "a")
somefile.puts "Hello file!"
somefile.close

so what i'd like to do is instead of adding it to the end of the file, add it to a specific line. The text file looks like this:

names
kyle
andrew
joshua
devon

so what I'd like to be able to do it to insert text between "kyle" and "andrew", with each on a seperate line. Please help

  • possible duplicate of [How to insert a string into a textfile](http://stackoverflow.com/questions/2139058/how-to-insert-a-string-into-a-textfile) – Jordan Running Apr 28 '15 at 23:01

1 Answers1

2

Random access is for read-only purpose, if you want to write a random line:

  • read the file
  • find the line you want to append text
  • append and write a new file
require 'stringio'
tmp = StringIO.open
origin.each do |line|
  tmp<<line
  if line == 'kyle'
    tmp << 'new line !'
  end
end
tmp.seek 0
File.open(fname, "wb").write tmp.read

the file then looks like:

names
kyle
new line !
andrew
joshua
devon
James B.C.
  • 21
  • 1