Ruby how to write to Tempfile Ruby how to write to Tempfile ruby ruby

Ruby how to write to Tempfile


You're going to want to close the temp file after writing to it. Just add a t.close to the end. I bet the file has buffered output.


Try this run t.rewind before read

require 'tempfile't = Tempfile.new("test_temp")t << "Test data"t.write("test data") # => 9IO.read t.path # => ""t.rewindIO.read t.path # => "Test datatest data"


close or rewind will actually write out content to file. And you may want to delete it after using:

file = Tempfile.new('test_temp')begin  file.write <<~FILE    Test data    test data  FILE  file.close  puts IO.read(file.path) #=> Test data\ntestdata\nensure  file.deleteend