Changes

Jump to: navigation, search

Ruby Directory Handling

2,643 bytes added, 02:51, 29 November 2007
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...
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:

<pre>
Dir.pwd
=> "/home/ruby"
</pre>

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:

<pre>
Dir.chdir("/home/ruby/test")
</pre>

== 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:

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

== 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 (.).

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

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

<pre>
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
</pre>

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

<pre>
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
</pre>

Navigation menu