Working with Files in Ruby

Follow Techotopia on Twitter Bookmark and Share

From Techotopia

Jump to: navigation, search
PreviousTable of ContentsNext
Ruby Directory HandlingWorking with Dates and Times in Ruby

Purchase and download the PDF and ePub versions of this Ruby eBook for only $8.99  Add to Cart

In the previous chapter we looked at how to work with directories. This chapter 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.


[edit] 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:

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:"temp.txt", "w")
=> #<File:temp.txt>

[edit] Opening Existing Files

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

file ="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 ="temp.txt", "r")
=> #<File:temp.txt>

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

=> false

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

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

[edit] 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:"tempfile.txt", "w")
=> #<File:tempfile.txt>

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

=> 1

[edit] Getting Information about Files

File handling often requires more than just opening files. Sometimes it is necessary to find out information about a file before it is opened. Fortunately the File class provides a range of methods for this very purpose.

To find out if a file already exists, use the exists? method:

=> true

To find out if the file is really a file as opposed to, for example, a directory use the file? method:

=> false

Similarly, find out if it is a directory with the directory? method:"ruby")
=> true

To identify whether a file is readable, writable or executable, use the readable?, writable? and executable? methods:

=> true

=> true

=> false

Get the size of a file with, yes you guessed it, the size method:

=> 99

And find if a file is empty (i.e zero length) with the zero? method:"temp.txt")
=> false

Find out the type of the file with the ftype method:

=> "file"

=> "directory"

=> "blockSpecial"

Finally, find out the create, modify and access times with ctime, mtime and atime:

=> Thu Nov 29 10:51:18 EST 2007

=> Thu Nov 29 11:14:18 EST 2007

=> Thu Nov 29 11:14:19 EST 2007

[edit] Reading and Writing Files

Once we've opened an existing file or created a new file we need to be able to read from and write to that file. We can read lines from a file using either the readline or each methods:

myfile ="temp.txt")
=> #<File:temp.txt>

=> "This is a test file\n"

=> "It contains some example lines\n"

Alternatively, we can use the each method to read the entire file:

myfile ="temp.txt")
=> #<File:temp.txt>

myfile.each {|line| print line }
This is a test file
It contains some example lines
But other  than that
It serves no real purpose

It is also possible to extract data from a file on a character by character basis using the getc method:

myfile ="Hello.txt")
=> #<File:temp.txt>

=> "H"
=> "e"
=> "l"

Needless to say, we can also write to a file using the putc method to write a character at a time and puts to write a string at a time - note the importance of the rewind method call. This moves the file pointer back to the start of the file so we can read what have written:

myfile ="write.txt", "w+")    # open file for read and write
=> #<File:write.txt>

myfile.puts("This test line 1")         # write a line
=> nil

myfile.puts("This test line 2")         # write a second line
=> nil

myfile.rewind                           # move pointer back to start of file
=> 0

=> "This test line 1\n"

=> "This test line 2\n"

Purchase and download the full PDF and ePub editions of this Ruby eBook for only $8.99

Add to Cart

PreviousTable of ContentsNext
Ruby Directory HandlingWorking with Dates and Times in Ruby
Personal tools

Find us on Facebook