0

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.

2
  • By the way, you can simplify the file output by passing a block to File.open: File.open( "stdout","w" ) { |output| output << "#{failPlaces.last}\n" }. Your file will be opened and closed for you automatically. Commented Jun 19, 2016 at 16:30
  • Thanks Keith, That makes it look better. Commented Jun 19, 2016 at 18:06

1 Answer 1

1

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

1 Comment

Thank you, I was using w(overwriting) whereas I should be using a(appending). Big help! thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.