Tuesday, January 19, 2010

Section 8.2. Creating a New File


Working with Files > Creating a New File




8.2. Creating a New File


To create a new file and open it at the same time, use the File method new, like this:

file = File.new( "file.rb", "w" ) # => #<File:file.rb>


The first argument names the new file, and the second argument specifies the file mode—r for readable, w for writable, or x for executable.


Table 8-1 shows the effect of the different modes.


































Table 8-1. File modes
Mode Description
"r" Read-only. Starts at beginning of file (default mode).
"r+" Read-write. Starts at beginning of file.
"w" Write-only. Truncates existing file to zero length or creates a new file for writing.
"w+" Read-write. Truncates existing file to zero length or creates a new file for reading and writing.
"a" Write-only. Starts at end of file if file exists; otherwise, creates a new file for writing.
"a+" Read-write. Starts at end of file if file exists; otherwise, creates a new file for reading and writing.
"b" (DOS/Windows only.) Binary file mode. May appear with any of the key letters listed above.













You can also create files using new with flags and permission bits. For more information, see http://www.ruby-doc.org/core/classes/File.html



 

 


No comments: