Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I save the text of puts in Ruby to a txt file?

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
like image 889
Courtney Lawton Avatar asked Sep 12 '14 21:09

Courtney Lawton


2 Answers

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.

like image 200
the Tin Man Avatar answered Sep 21 '22 02:09

the Tin Man


Is this what you looking for ? You can open madlib_output.txt file in append mode and whatever you want to write will be inside the block eg: "hi"

File.open("madlib_output.txt","a") do |f|
 f.puts "hi"
end
like image 36
Rahul Dess Avatar answered Sep 18 '22 02:09

Rahul Dess