Basic File and Directory Operations in Ruby

This article will cover several different ways of interacting with files and directories.


Published on:December 16, 2013

Ruby provides a number of mechanisms for reading and writing files, listing directories, etc. This article will cover several of the more basic items. Let's get to it shall we?

Listing Files

You can quickly and easily list all files in a directory using Dir.glob.


Dir.glob("*") # => Lists all files in the current directory and all subdirectories
Dir.glob("*.jpg") #=> Lists only jpg files in the current directory
Dir.glob(["*.jpg", "*.png"]) #=> Lists both jpg and png files in the current directory
Dir["*.jpg","*.png"] #=> The short form of dir.glob.  It's equivalent to Dir.glob([])

You can also use patterns with Dir.glob.


Dir.glob("ruby.ex?") #=> ruby.exe
Dir.glob("*.[a-z][a-z]") #=> Returns anything with a 2 digit extension
Dir.glob("*.{exe,dll}")  #=> Returns exe and dll files

You can also loop through each filename using Dir.foreach.


Dir.foreach(".") do |file|
  puts file
end

Getting and Changing Directories

To get the current directory, use Dir.pwd. In addition we can also get the user's home directory with Dir.home.


Dir.pwd # => Returns the current directory.
Dir.home  # => Returns the user's home directory.
Dir.home("root") # => Returns the root user's home directory.

You can also change the directory using Dir.chdir.


Dir.pwd # => /opt/mysite/current
Dir.chdir("/") # => Current directory is now root.
Dir.chdir("/root") # => Current directory is now root
Dir.chdir("..") # => Current directory is now /

Creating and Deleting Directories

We can create directories with Dir.mkdir and delete directories with Dir.rmdir. Note that the directory must be empty in order to be deleted.


Dir.mkdir("RubyTest") #=> Creates a directory called RubyTest
Dir.rmdir("RubyTest") #=> Removes the RubyTest directory

Determine Whether a Directory Exists

You can determine whether a directory exists with Dir.exists?.


Dir.exists?("mydir") #=> Returns true if the directory exists, or false if otherwise.

Building Paths

Windows tends to have different path separators from the rest of the world, Therefore, it is recommended that you use File.join to build up your paths. For example:


home = Dir.home
File.join(home, ".ssh") #=> /root/.ssh or C:/Users/MyUser/.ssh depending on the platform.

Hardcoding the path makes your code incompatible with either Linux, OS X, or Windows. For example:


ssh_folder = "/root/.ssh" #=> Doesn't work on windows.
ssh_folder = "C:/Users/MyUser/.ssh" #=> Doesn't work on linux or OS X.

You can also get the absolute path of a file using File.absolute_path.


File.absolute_path("current") #=> /opt/mysite/current

You can get the base name of the file as well using File.basename.


File.basename("/etc/init.d/mysqld") #=> mysqld

Finally, you can expand a given path to the full path using File.expand_path.


File.expand_path("~/Documents") #=> C:/Users/Bob/Documents
File.expand_path(".")  #=> /opt/mysite/current

Reading and Writing Files

You can either open an existing file or create a new file with File.open. Note that the default 'w' flag overwrites the old file. Use the 'a' flag to append to an existing file.


f = File.open("log.txt", "w")
f.close #=> Make sure you close the file after you open it.

You can delete files with File.delete.


File.delete("log.txt") #=> deletes log.txt.

Writing to files is easy. Just use the write method.


f = File.open("log.txt", "w")
f.write("Warning: some really crazy stuff just happened!\n")
f.write("Warning: I don't know what to do!\n")
f.close #=> Make sure you close the file after you open it.

You can also use the methods below to read the file.


f = File.open("log.txt", "r")
f.read(3) #=> returns 'War' from the example earlier.
f.rewind #=> moves the file pointer back to the beginning of the file.
f.read(3) #=> returns 'War' again
f.rewind #=> moves the file pointer back to the beginning of the file.
f.seek(3)  #=> moves the file pointer to the third position in the file.
f.read(3) #=> returns 'nin'
f.rewind #=> moves the file pointer back to the beginning of the file.
f.readline #=> returns "Warning: some really crazy stuff just happened!\n"
f.rewind #=> moves the file pointer back to the beginning of the file.
f.read  #=> reads the entire file.

For more information you can consult the following resources.

That's it and thanks for reading!