Ruby Dir: How to Use Dir Function to Manipulate and Navigate Directories

Ruby DirRuby is an important and widespread server-side scripting language. It was invented in 1993 by Yukihiro Matsumoto of Japan. This language has features similar to that of Smalltalk, Perl and Python. Since it has easy syntax new programmers find it easy and quick to learn. Ruby is also a true object oriented -language. It is open source and freely available on the web. Ruby is an interpreted programming language used to create Internet and intranet applications. Also it is used  to develop CGI(Common Gateway Interface) code. The language is known for easy connectivity to major databases such as Oracle, DB2, Sybase and MySQL. Other notable features of this language include scalability and ease of maintainability. Moreover, it supports several GUI tools and incorporates powerful built-in functions. Today, we walk you through the Ruby DIR function in this Intermediate level tutorial. We assume that you know the basics of operating system and file concepts. Else we suggest that you go through this basic Ruby course, specially designed for those with no prior programming experience.

What is a Directory?

A directory is a location where the files are stored on the computer. They are found in hierarchical file system such as DOS, OS/2, Unix and more.  A directory contained inside another directory is known as a sub-directory. The terms parent and child are used to refer to the relation between a subdirectory and directory of which the sub-directory belongs. Generally, files are organized by storing related files in a single directory.  In Ruby, the Dir class is responsible for handling directories.

Commands to Navigate Directories

  • Dir.chdir(argument)

To change directories, use Dir.chdir() command. The argument passed is the directory you wish to change to from the current directory. The parameter must be a string, either an absolute or relative path. To change the current working directory to its parent directory, the directory name passed as argument to the chdir command should be ‘..’. See the example below.

Dir.chdir("/company/cust")
  • Dir.pwd

This command returns the current working directory as a string.  Take a look at the example.

puts Dir.pwd -/company/cust
  • Dir.mkdir(argument)

This command will create a new directory in the current working directory. You can pass a relative or absolute path as the parameter. Note that this command will fail if a directory with the same name already exists. It can also fail if you are not given the privileges to create a directory at that location.

Dir.mkdir("NewCompany")

When you create a new directory, you can set privileges to it.

Dir.mkdir("NewCompany", 755)

In this example, the mask 755 set privileges owner, group, world to rwxr-xr-x where r= read, w=write and x=execute.

  • Dir.entries(argument)

This command accepts a directory as an argument and returns an array of files in the specified  directory as strings. Note that it returns the files and directories even from the directories “.” and “..”. Also note that the directory listing is only one level deep. In other words the files and directories further levels down are not returned.

puts Dir.entries("/company/cust").join(' ')
  • Dir.delete(argument)

Use this command to delete a directory from the file system. You can also use Dir.rmdir(argument) or Dir.unlink(argument) to get the same result. However, this command will work on empty directories only. In case there are files or directories in the directory to be deleted, this method will not work.

Dir.delete("NewCompany")
  • Dir.foreach(directory) {|f| … }

You can use this command to iterate over all of the files in the requested directory. Secondly, the name of the files are passed as the string to the block. This is similar to calling Dir.entries(directory).each {|f| … }.

To see how these commands are used in the Ruby language, you can take this practical Ruby training, or just read on.

How to Create Temporary Directories

Temporary files are created briefly during a program’s execution. The command Dir.tmpdir gives the path to the temporary directory on the current system. Note that this method is not available by default. You have to explicitly make the declaration to make this command available. Take a look at the example below.

require 'tmpdir'
tempfilename = File.join(Dir.tmpdir, "new_temp")
tempfile = File.new(tempfilename, "w")
tempfile.puts "This is a new temporary file"
tempfile.close
File.delete(tempfilename)

In this program, a temporary file is created. Then puts is used to write data to it. The file is closed and the delete command is called with the file name as argument. So in the end, the file is deleted from the system. To learn more about how Ruby handles this, you can read further in this step by step tutorial.

Program to Create Temporary Files Using the Ruby Standard Library

require 'tempfile'
f = Tempfile.new('twinkle')
f.puts "Hello"
puts f.path
f.close

Here the Ruby library called Tempfile creates the temporary files.

How to Use Glob with Directories

The glob method returns all the files which match the “globbing” rules as an array which can be saved for subsequent use or iterated over. By using Dir.glob, you can use regular expression like pattern matching to select specific files. However, remember that these appear similar to regular expressions, in practice they are not. Note that they are more similar to shell expansion wildcards rather than regular expressions.

  • '*'- Matches zero or more characters. A glob which consists of this symbol'*', and no other characters  or wildcards will match all files in the current directory. Usually, the asterisk  is combined with a   file extension to narrow down the search.
  • '**'- This matches all directories recursively. It finds all the files in sub-directories of the current directories.
  • '?'- This wild card character matches any one character. It is convenient for searching files whose name are in a specific format. For example, 3 characters and a .txt extension could be represented as "???.txt."
  • [a-z]- It matches any character in the character set. The set could be either a list of characters or a range specified by the hypen character.
  • {a,b}- This matches pattern a or b. Note that it is not a regular expression quantifier even though it looks like one.

To advance your knowledge on operating systems, we recommend this course on Linux operating system concepts.

One of the factors to consider is the case sensitivity. In Windows it does not matter. However, if your operating system is Linux or any version of Unix, then the uppercase letters are considered different from the lower case letters. For example, new.docx and New.docx refer to the same file on Windows. However, in Linux these are considered different files.

Example Demonstrating the Different Pattern Matching Using the Dir Command

 #!/usr/bin/env ruby
  • Dir['*.xml'] - Here the command extracts all files with file extension '.xml'.
  • Dir['?????.jpg']- This returns all files with five characters and extension '.jpg'
  • Dir['*.{jpg,png,gif}']-  Displays all the files ending with '.jpg', '.png' and '.gif'
  • Dir['**/*.jpg']- Returns all the files ending with '.jpg' in the current directory as well as the sub-directories
  • Dir['Spe**/*.jpg']- Descends into directories starting with 'Spe' and returns all the files ending with '.jpg.' Note that this command descends only one directory.
  • Dir['Spe**/**/*.jpg'] - Descends into directories starting with 'Spe' and also all their subdirectories and returns all the files ending with '.jpg.'

Directory Instance Methods

Here are some commonly used methods. Assume d is an instance of Dir class.

  • d.close - This command closes the directory stream.
  • d.pos/d.tell - This returns the current position in d.
  • d.pos = offset - This command sets the location in the directory stream.
  • d.read - It returns the next entry from d.
  • d.rewind- This command move the position in d to the very first entry.

Go through the examples above and make your own programs. This will increase your proficiency in using Dir commands in your Ruby programs to achieve desired results. You may also want to take this course that teaches Ruby from scratch, to help you get   a better grasp on it. Once you’re ready to move to the next level, take this advanced Ruby course to help you gain mastery.