Black Bytes
Share this post!

Working with files and folders

Data processing is a common task in programming. Data can come from many places: files, network, database, etc. In this post you will learn how to work with files and folders in Ruby.

files and folders ruby

Reading files

The file class allows you to open a file by simply passing in the file name to the open method:

Since File is a sub-class of the IO class, you can work with file objects using IO methods. For example, using gets you can read one line at a time, and using read you can read the whole file or a specified number of bytes.

You will need to remember to call close on your file, so the contents are flushed to disk (if you wrote to it) and the file descriptor is made available.

If you want to read the whole file with just one line of code you can use, in this case you don’t need to close the file. There is also a File.write counterpart to this method.

If you want to process the file one line at a time, you can use the foreach method:

Writing to files

File writing is pretty easy too. When opening a file for writing, we need to add the “w” flag as the second argument.

This will rewrite the previous file contents. If you want add to the file, use the “a” (append) flag.

Another way to write data into a file is to use File.write:

File & directory operations

Other than reading and writing there are other operations you may want to do on files. For example, you may want to know if a file exist or get a list of files for the current directory. Let’s see a few examples:

The last example makes more sense if we are looping through the contents of a directory listing.

Using Dir.glob you can get a list of all the files that match a certain pattern, here are some examples:

Documentation links