Reputation: 105
I want to output data(integers) onto a file called stdout.txt. The trouble seems to be that my code overwrites the existing data in the file instead of adding to it line by line.
if failPlaces.empty? == false
puts "position: #{failPlaces.last}"
output = File.open( "stdout","w" )
output << "#{failPlaces.last}\n"
output.close
else
puts "He Passes it!!!!!!!!!!!!!!!!!"
output = File.open( "stdout","w" )
output << "Pass\n"
output.close
end
I would like to understand why my code is behaving like this and what the solution would be.
Upvotes: 0
Views: 75
Reputation: 2302
Given a file named stdout.txt you can write it as such (remember to use a
rather than w
). w
will overwrite everything in the file whereas a
will append if file exists, otherwise creates a new file.
Here is a list of Ruby IO modes
failPlaces = [1, 2]
if failPlaces.empty?
puts "He Passes it!!!!!!!!!!!!!!!!!"
output = File.open('stdout.txt', 'a')
output << "Pass\n"
output.close
else
puts "position: #{failPlaces.last}"
output = File.open('stdout.txt', 'a')
output << "#{failPlaces.last}\n"
output.close
end
Upvotes: 1