Ruby Directory Handling

From Techotopia
Revision as of 02:51, 29 November 2007 by Neil (Talk | contribs) (New page: It may have escaped your notice, but up until this chapter everything we have done involved working with data in memory. Now that we have covered all the basics of the Ruby language, it is...)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

It may have escaped your notice, but up until this chapter everything we have done involved working with data in memory. Now that we have covered all the basics of the Ruby language, it is time to turn our attention to working with files and directories in Ruby.

Changing Directory in Ruby

When a Ruby application is launched it is usually done from a particular directory. Often it is necessary to navigate to a different directory somewhere on the filesystem from within the Ruby code. Ruby provides a number of useful directory navigation methods in the Dir class.

First, it is often usefl to identify the current directory. This can be done with the pwd methods of the Ruby Dir class:

Dir.pwd
=> "/home/ruby"

Changing the current working directory in Ruby is achieved using the chdir method of the Ruby Dir class. This methods takes the path of the destination directory as an argument:

Dir.chdir("/home/ruby/test")

Creating New Directories

Directory creation in Ruby is handled by the mkdir method of the Dir class. This method takes as its argument the path of the new directory. this can either be a full path to the directory, or a relative path based on the current working directory:

Dir.mkdir("/home/ruby/temp")
=> 0

Directory Listings in Ruby

Once we have navigated to the desired directory it is a common requirement to obtain a listing of files contained within that directory. Such a listing can be obtained using the entries method. The entries methods takes as an argument the path of the directory for which a listing is required and returns an array containing the names of the files in that directory:

In the following example we request a listing of the files in the current directory, which is represented by a dot (.).

Dir.entries(".")
=> ["techotopia_stats.jpg", "toolButton_IST.png", ".", "..", "techotopia_stats_since_start.jpg", "music_728x90_1.jpg", "music_468x60_a.jpg", "Fedora_essentials.jpg"]

We can use some of the techniques covered in Understanding Ruby Arrays to extract the elements from the array:

 dirListing.each { |file| puts file }
techotopia_stats.jpg
toolButton_IST.png
.
..
techotopia_stats_since_start.jpg
music_728x90_1.jpg
music_468x60_a.jpg
Fedora_essentials.jpg

Alternatively, we can utilize the foreach method of the Dir class to achieve the same result:

Dir.foreach(".") { |file| puts file }
techotopia_stats.jpg
toolButton_IST.png
.
..
techotopia_stats_since_start.jpg
music_728x90_1.jpg
music_468x60_a.jpg
Fedora_essentials.jpg