Changes

Working with Files in Ruby

1,198 bytes added, 15:59, 29 November 2007
Creating a New File with Ruby
<tr>
</table>
 
With this information in mind we can, therefore, create a new file in "write" mode as follows:
 
<pre>
File.new("temp.txt", "w")
=> #<File:temp.txt>
</pre>
 
== Opening Existing Files ==
 
Existing files may be opened using the ''open'' method of the ''File'' class:
 
<pre>
file = File.open("temp.txt")
=> #<File:temp.txt>
</pre>
 
Note that existing files may be opened in different modes as outlined in the table above. For example, we can open a file in read-only mode:
 
<pre>
file = File.open("temp.txt", "r")
=> #<File:temp.txt>
</pre>
 
It is also possible to identify whether a file is already open using the ''closed?'' method:
 
<pre>
file.closed?
=> false
</pre>
 
Finally, we can close a file using the ''close'' method of the Ruby ''File'' class:
 
<pre>
file = File.open("temp.txt", "r")
=> #<File:temp.txt>
file.close
=> nil
</pre>
 
== Renaming and Deleting Files in Ruby ==
 
Files are renamed and deleted in Ruby using the ''rename'' and ''delete'' methods respectively. For example, we can create a new file, rename it and then delete it:
 
<pre>
File.new("tempfile.txt", "w")
=> #<File:tempfile.txt>
 
File.rename("tempfile.txt", "newfile.txt")
=> 0
 
File.delete("newfile.txt")
=> 1
</pre>