I\'m trying to create a new file and things don\'t seem to be working as I expect them too. Here\'s what I\'ve tried:
File.new \"out.txt\"
File.open \"out.tx
The directory doesn't exist. Make sure it exists as open
won't create those dirs for you.
I ran into this myself a while back.
If the objective is just to create a file, the most direct way I see is:
FileUtils.touch "foobar.txt"
File.new
and File.open
default to read mode ('r'
) as a safety mechanism, to avoid possibly overwriting a file. We have to explicitly tell Ruby to use write mode ('w'
is the most common way) if we're going to output to the file.
If the text to be output is a string, rather than write:
File.open('foo.txt', 'w') { |fo| fo.puts "bar" }
or worse:
fo = File.open('foo.txt', 'w')
fo.puts "bar"
fo.close
Use the more succinct write
:
File.write('foo.txt', 'bar')
write
has modes allowed so we can use 'w'
, 'a'
, 'r+'
if necessary.
open
with a block is useful if you have to compute the output in an iterative loop and want to leave the file open as you do so. write
is useful if you are going to output the content in one blast then close the file.
See the documentation for more information.