Create a File with Ruby Tutorial
In this lesson, we are going to learn how to work with files in Ruby, including how to create, edit and append. This information can be particularly helpful when you want to store content on a text file, so that you don't have to rely on a database connection every time. It's good to have some practical knowledge on this.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

In this guide we are going to learn how to work with files in Ruby, including how to create, edit and append to a file. This information can be particularly helpful when you want to store content in a data in a file so that you don't have to rely on a database connection every time. It's good to have some practical knowledge on this.

Ruby File Class

First off, we are going to see how to create a file.

File.open("files-lessons/teams.txt" , 'w+')  { |f| f.write("Twins, Astros, Mets, Yankees") }

In this code, I'm calling a core Ruby class called File and I'm passing two values as the parameters to its open method. The first parameter is the path where I want my text file to be located, and the second is the options that I want to do with the file. In this case, w+ stands for reading and writing.

Other options you can pass as the second option

  • r stands for reading
  • a stands for appending to a file
  • w stands for just writing to a file
  • w+ stands for reading and writing to a file
  • a+ stands for opening a file for reading and appending
  • r+ stands for opening a file for updating, and includes both reading and writing.

Going back to the code, the variable f is the block variable and we are asking it to write all the values that are present inside the double quotes by passing the method write to it.

If you run this code, it should create a text file called teams and should add the names of the four teams inside it.

To run it, go to the terminal and type the code (or run it from wherever you have saved it on your system):

ruby files-lessons/creating_a_file.rb

Now, if you go back to the files-lessons file, you can see a new file called teams.txt and if you open it, you can find Twins, Astros, Mets, Yankees in it.

There is also another way to accomplish this functionality for your future reference.

file_to_save = File.new("files-lessons/otherteams.txt" , 'w+')
file_to_save.puts("A's, Diamondbacks, Mariners, Marlins")
file_to_save.close

Now, if you run this code, you can see the file otherteams.txt and this has the content A's, Diamondbacks, Mariners, Marlins.