Working with directories in Ruby is an essential skill to have in order to become a proficient programmer. Luckily working with directories is just as straightforward as working with files. The most basic keywords, methods and syntax that are indispensable to remember are as follow:
Utilizing the Directory class in combination with File class allows us to manipulate files and directories in any way possible. Ruby have a special keyword called __FILE__ that represents the current directory. If we run __FILE__ in combination with dirname we get a representation of the current directory.
File.dirname(__FILE__) è “.”
If we combine the representation of the current directory along with the expand_pathmethod which gives us the current path we get our current directory path.
File.expand_path(File.dirname(__FILE__)) èfull path to the current directory
Using File.dirname(__FILE__) is different from using Dir.pwd, found in the Directory class. Dir.pwdrepresents the present working directory while when we use File.dirname(__FILE__) we are asking for the current directory path relative to this file. This is more useful because we could move around directories by using Dir.chdir and telling it where we want to go.
To go back a directory we pass ‘..’ to Dir.chdir . It could take an absolute path as well as a relative path.
Dir.chdir(‘..’) è 0
To list the contents of a directory we use Dir.entries and tell it which directories to display the content.
Dir.entries(“.”) è displays all the files in an array
Since the entries method displays its results in an array gives us the ability to sort the files if we want to or pass each one to an enumerable. The possibilities are endless.
Dir.entries(“.”).each do |entries|
puts entries + “:”
Since looping the directory files is such a common task that ruby provide us with foreach method which works the same way as the each enumerable.
We also have the ability to make directories using Dir.mkdir and providing it with a directory name.
We also have the ability to delete directories using the delete method. Dir.delete
The delete method only work if the directory is empty. To delete directories that are not empty we could use the Fileutil class the we used previously.
That is the basics on working with directories and files.