0

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?

5
  • 1
    Define "not processed" Commented Feb 22, 2018 at 17:46
  • I do not see printed on screen the content of the file Commented Feb 22, 2018 at 17:47
  • 1
    But this is something else entirely, isn't it? I assure you, it is being processed just fine. Evident from the fact that your program doesn't crash. Commented Feb 22, 2018 at 17:51
  • It's like you come to a doctor and declare "I have lupus". No, you most likely don't, you just made an incorrect conclusion based on incomplete data. Wording and precision is important. As are basic debugging skills. This case was simple enough that we were able to just see it. But if you had a more complicated scenario, no minimal reproducible example and no triage, then you'd be left with a few downvotes instead of an answer. Commented Feb 22, 2018 at 17:59
  • The above is to say: "it is very useful to be able to do some basic investigation by yourself". You won't be able to always rely on stackoverflow for fixing bugs :) Commented Feb 22, 2018 at 17:59

1 Answer 1

2

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) 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.