Creating a file
In this section, we will 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 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 of 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
Following is the list of the options you can pass as the second option:
r
: This stands for readinga
: This stands for appending to a filew
: This stands...