I wrote a madlib in Ruby, and want to save the resulting madlib to a txt file. This is what I wrote, but the resulting txt file is empty:
file=File.open("madlib_output.txt","a")
file.puts
file.close
There are ways to save the output of a script to a file without having to modify every puts
in the script.
The easiest is to route the output at the command-line using redirection. Running a script with > some_file
at the of the command will route all STDOUT to the file. Similarly, using > some_file 2>&1
will route both STDOUT and STDERR to the same file. This won't capture anything typed in at a gets
as the code waits for input though, because that won't count as program output.
If you don't mind changing your code a little, you can temporarily change the interpreter's idea of what STDOUT is by reassigning it to a file:
old_stdout = $stdout
File.open('output.txt', 'w') do |fo|
$stdout = fo
# ----
# your code goes here
puts "hello world"
# ----
end
$stdout = old_stdout
Run that, then look at the file "output.txt" and you'll see "hello world", even though we didn't print to the file-handle fo
directly, like we would normally do using fo.puts
.
There are a variety of ways of doing the same thing but they amount to pointing STDOUT or STDERR somewhere else, writing to them, then resetting them.
Typically, if we intend from the start to output to a file, then we should use a File.open
block:
File.open('output.txt', 'w') do |fo|
fo.puts "hello world"
end
The benefit of that is the file will be closed automatically when the block exits.