Reputation: 63
I have this snippet of code:
File.open(input, "w+").each do |line|
puts "Enter line content, or \"-EOF-\" to stop inputting."
input = gets.chomp
if input == "-EOF-"
break
else
line.puts input
end
end
It creates the file, but it doesn't do anything else that's specified. Why is that?
Upvotes: 0
Views: 74
Reputation: 6062
A couple of problems here.
One, you're using the filename variable File.open(input...
also as a variable for what the user enters (input = gets.chomp
). Don't do that.
Secondly, when you open an existing file for writing with w+
you truncate it to zero length. Your loop is actually a block at that point. If you were reading, that would be a different story.
Try opening the file and assigning it to a variable:
f = File.new(input, "w+")
Then run a loop (begin...end while
) that gets input and writes it to f
as follows:
userstuff = gets.chomp
f.write(userstuff)
Don't forget to close the file when you are finished writing to it:
f.close
Upvotes: 0
Reputation: 114178
It creates the file, but it doesn't do anything else that's specified. Why is that?
Because you call File.open(...).each
instead of just File.open(...)
– you want to open the file, not traverse its content.
That aside, you don't have to invent your own EOF handling. Hitting Ctrl-D will generate an EOF indicator which in turn results in gets
returning nil
.
This allows you to have a simple loop:
File.open(input, 'w+') do |file|
puts 'Enter lines, or hit "Ctrl-D" to stop inputting.'
while line = gets
file.puts line
end
end
Upvotes: 2
Reputation: 18784
It looks to me like what you are trying to accomplish is writing to the file. Here's a lightly modified version that echo's what you have written and adds it as a new line in the file:
input = 'test.txt'
File.open(input, "w+") do |file| # File open returns the file, not it's lines
loop do
puts "Enter line content, or \"-EOF-\" to stop inputting."
input = gets # no chomp here, because we probably want that in the file
if input.chomp == "-EOF-" # chomp here to compare with `"-EOF-"` instead of "-EOF-\n"
break
else
file << input # this writes your input line to the file
puts input
end
end
end
Upvotes: 0
Reputation: 30056
Because you're creating a new file and that's empty, so no lines, no blocks executed. If you want to enter into the loop, that file should contain some lines and you need to open it in append mode
File.open(input, "a+")
Upvotes: 0