Bill Bisco Bill Bisco - 29 days ago 11
Ruby Question

Ruby: Simple Creating & Writing a New File

I can create a Text File in Ruby, but my current code does not let me write to that new file. Any help would be appreciated.

newfilename = "16.Sample2.txt"
line1 = "BOOYAH"

out_file = File.new(newfilename, "w")
out_file.close
out_file = open(filename, 'w')
out_file.write(line1)

Answer Source

The only real bug in your code is that you accidentally typed filename instead of newfilename. Make that simple change and this code will work perfectly:

newfilename = "16.Sample2.txt"
line1 = "BOOYAH"

out_file = File.new(newfilename, "w")
out_file.close
out_file = open(newfilename, "w")
out_file.write(line1)

That being said, you could make this code a lot better. open() is a generic method which lets you open any IO stream, including files and process pipes. File.open() is a much nicer method for handling files. It will automatically create a file if it doesn't exist, so you can simplify your code:

newfilename = "16.Sample2.txt"
line1 = "BOOYAH"

out_file = File.open(newfilename, "w")
out_file.write(line1)
out_file.close

But wait, it gets better! If you pass a block to File.open(), it will automatically close the file at the end of the block, so you don't have to remember to close it!

newfilename = "16.Sample2.txt"
line1 = "BOOYAH"

File.open(newfilename, "w") do |out_file|
  out_file.write(line1)
end

Using File.open with a block is what experienced rubyists generally prefer to do.