When I run the following code taken from the Learn Ruby the Hard Way Course Exercise 16,
filename = ARGV.first
target = open(filename, 'w+')
puts "Now I'm going to ask you for three lines."
print "line 1: "
line1 = $stdin.gets.chomp
print "line 2: "
line2 = $stdin.gets.chomp
print "line 3: "
line3 = $stdin.gets.chomp
puts "I'm going to write these to the file."
target.write(line1 + "\n" + line2 + "\n" + line3)
puts "And now I'm going to print the file to prove I have altered it."
puts target.read
puts "And finally, we close it."
target.close
the line puts target.read
does not print the three input lines, even though the text file does change.
I have tried changing the mode used by the open
method and adding a new open
method before calling the read
method. Creating a separate program with the same script to read and print text file works as expected.
How can I read a file I have just written to? Why does it not work when I write and read within the same program?