Working with Files in Ruby

Revision as of 15:59, 29 November 2007 by Neil (Talk | contribs) (Creating a New File with Ruby)

Revision as of 15:59, 29 November 2007 by Neil (Talk | contribs) (Creating a New File with Ruby)

In the previous chapter we looked at how to work with directories. This chapter we will look in detail at how to create, open and read and write to files in Ruby. We will then learn how to delete and rename files.

Creating a New File with Ruby

New files are created in Ruby using the new method of the File class. The new method accepts two arguments, the first being the name of the file to be created and the second being the mode in which the file is to opened. Supported file modes are shown the following table:

ModeDescription
rRead only access. Pointer is positioned at start of file.
r+Read and write access. Pointer is positioned at start of file.
wWrite only access. Pointer is positioned at start of file.
w+Read and write access. Pointer is positioned at start of file.
aWrite only access. Pointer is positioned at end of file.
a+Read and write access. Pointer is positioned at end of file.
bBinary File Mode. Used in conjunction with the above modes. Windows/DOS only.

With this information in mind we can, therefore, create a new file in "write" mode as follows:

File.new("temp.txt", "w")
=> #<File:temp.txt>

Opening Existing Files

Existing files may be opened using the open method of the File class:

file = File.open("temp.txt")
=> #<File:temp.txt>

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:

file = File.open("temp.txt", "r")
=> #<File:temp.txt>

It is also possible to identify whether a file is already open using the closed? method:

file.closed?
=> false

Finally, we can close a file using the close method of the Ruby File class:

file = File.open("temp.txt", "r")
=> #<File:temp.txt>
file.close
=> nil

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:

File.new("tempfile.txt", "w")
=> #<File:tempfile.txt>

File.rename("tempfile.txt", "newfile.txt")
=> 0

File.delete("newfile.txt")
=> 1