Asarluhi
Asarluhi

Reputation: 1290

Reading a file after writing on it

I am doing exercise 16 at learnrubythehardway.org.
The name of a file is passed as argument to the following script, which asks the user to write three lines to the file:

filename = ARGV.first

puts "Opening the file..."
target = open(filename, 'w+')

puts "Now I am 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 am going to write these to the file."
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")

puts "Here is your new file:"
print target.read

puts "And finally we close it"
target.close

Just before closing the file I would like the user be given the opportunity to see the content of the new file, however that part of the code is not processed. Why is that?

Upvotes: 0

Views: 28

Answers (1)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230346

You have to rewind the file, if you want to read what you have just written.

target.write(line3)
target.write("\n")

target.rewind
target.read 

Bonus content

Use puts, it writes the newline for you.

target.puts(line3)

Upvotes: 2

Related Questions