I need to read the data out of database and then save it in a text file.
How can I do that in Ruby? Is there any file management system in Ruby?
I need to read the data out of database and then save it in a text file.
How can I do that in Ruby? Is there any file management system in Ruby?
Zambri's answer found here is the best.
where your options for
<OPTION>
are:r
- Read only. The file must exist.w
- Create an empty file for writing.a
- Append to a file.The file is created if it does not exist.r+
- Open a file for update both reading and writing. The file must exist.w+
- Create an empty file for both reading and writing.a+
- Open a file for reading and appending. The file is created if it does not exist.In your case,
w
is preferable.To destroy the previous contents of the file, then write a new string to the file:
To append to a file without overwriting its old contents:
The Ruby File class will give you the ins and outs of
::new
and::open
but its parent, the IO class, gets into the depth of#read
and#write
.For those of us that learn by example...
Write text to a file like this:
BONUS INFO ...
Read it back like this
Frequently, I want to read a file into my clipboard ***
And other times, I want to write what's in my clipboard to a file ***
*** Assumes you have the clipboard gem installed
See: https://rubygems.org/gems/clipboard
This is preferred approach in most cases:
When a block is passed to
File.open
, the File object will be automatically closed when the block terminates.If you don't pass a block to
File.open
, you have to make sure that file is correctly closed and the content was written to file.You can find it in documentation:
Are you looking for the following?