Creating a Text File with Ruby

Seann Branchfield
Sep 8, 2019 · 2 min read

Aside from using the Rails framework, there are some other practical applications of Ruby. One of them is being able to create a text file.

This is done using the .open method from the File class.

The first argument is the file name you are creating and “w” specifies that you are creating a new writable file. At this point you could also immediately write something to the file by adding one the same line:

{|f| f.write(“hello world”)}

Alternatively, you can append text to the file later like this:

The “a” stands for append.

If simply reading an existing file is your goal, you can use “r” in the .open method instead.

Considerations

In terms of the layout of your .txt file, you may want to make use of the newline character, “\n”, where needed. I actually used this in conjunction with the .join method. It was easiest for me to create my text planned out line by line as an array first. When I wanted to make it into a string, I was able to conveniently join all of the elements with newline characters, giving me the layout I was looking for.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade