The Ruby File Class

I recently completed a take home code challenge that involved picking a random word from a .txt file. My first reaction upon reading the requirements was, ‘ok, that’ll be easy.’ I started doing some Ruby stuff, created a class, initialized some variables, and then I got to the part where I needed a random word from a file. It hit me I had no idea how to do that. I figured there must be a way to access another file via require-relative maybe, I wasn’t sure. Some googling revealed Mama Ruby has a File class, and that sounded exactly like what I needed.

File is an abstraction of any accessible file. It contains several class methods that let you read the contents of the external file, either saved in memory or not, and then interpret the data in various ways. The .size method returns an integer of the file size in bits. .path returns the pathname as a string. There are also a few methods that return the file’s content, either in blocks, or as a whole, as a string. This sounds pretty hugely useful.

For example, if we wanted to select a random word from a text file, which was my original goal before looking into the File class, we might choose to use the .read method. Ruby would open the file, read all its contents, close the file, and then return the entire file’s content as a string. My text file of English words isn’t terribly large, but given a larger file this might not be terribly space efficient.

Ruby does also let us call .foreach on files, which reads each line in the file as a block and executes based on that. Using this method, we can read the file without its entire content having to be stored in memory at the same time. Going back to my example, let’s use .foreach to read through the text file of words to randomly select one.

Some of you might have clicked on the link to the docs, and realized, ‘wait, neither .read nor .foreach appear as methods for File‘. And you’d be right. They are actually inherited from the IO parent class. It is “the basis of all input and output in Ruby.”

I/O stands for Input/Output. An I/O device sends or receives data to and from a computer. Monitors, keyboards, etc., are all I/O devices. Reading from and to files sounds a lot like I/O, which is exactly why the classes are closely connected in Ruby. The docs reveal that File is the only standard subclass of IO.

We’ve fallen into a bit of a rabbit hole, but the main goal of this post was to give a basic overview of the Ruby File class, which provides great tools for reading and interpreting outside files in your Ruby apps.

Tags:,

Add a Comment

Your email address will not be published. Required fields are marked *