scerrecrow
scerrecrow

Reputation: 269

File not being created in Ruby script

I am trying to open a non existent file and write to it, however when I run the script, no file is being created.

Here is the line of code

File.open("valid_policies.txt", 'a+').write(policy_number.to_s + "\n")

Upvotes: 0

Views: 598

Answers (2)

the Tin Man
the Tin Man

Reputation: 160601

You're using:

File.open("valid_policies.txt", 'a+').write(policy_number.to_s + "\n")

That's a non-block form of open which doesn't automatically close the file. That means the data is most likely not being written to the file but is sitting in the IO buffer waiting to be flushed/synced. You could add a close but that only propagates non-idiomatic code.

Instead you can use:

File.write("valid_policies.txt", policy_number.to_s + "\n")

File.write automatically creates then writes to the file then closes it. It will overwrite existing files though.

If you aren't sure whether the file exists and want to create it if it doesn't, or append to it, then you use File.open with the a mode instead of a+. From the mode documentation:

"a" Write-only, each write call appends data at end of file. Creates a new file for writing if file does not exist.

Using a+ will work but it unnecessarily opens the file for reading also. Don't do that unless you're sure that's what you have to do.

If I needed to append I'd use:

File.open('valid_policies.txt', 'a') do |fa|
  fa.puts policy_number
end

That's idiomatic Ruby. puts will automatically "stringify" policy_number if it has a to_s method, which it should have since you're already calling it, and it'll also automatically add the trailing "\n" if it doesn't exist at the end of the string. Also, using the block form of open will automatically close the file when the block exists, which is smart house-keeping.

Upvotes: 0

jkeuhlen
jkeuhlen

Reputation: 4517

Instead of using .write try this instead:

File.open("valid_policies.txt", 'a+') {|f| f.write(policy_number.to_s + "\n") }

Upvotes: 3

Related Questions