We all have came across handling files in some way. Be it a .txt file or a .dat or even a .py file that we use to write our Ruby Programmes.
So, files are something, where we store some information.
Say for example, we want to write the below paragraph to a file.
So, we want to store the four lines in a File and name the File as myfirstfile.txt.
And in general, you need to follow the below steps create the file and write the lines :
Again, if you want to make some changes to the file(Say adding or deleting a few lines) :
Similarly, if you want to delete the myfirstfile.txt :
Now, let us corelate, how can we achieve the same in Ruby.
The first thing is to open a file. And to open a file in Ruby, there is a Method called File.new() that accepts two Arguments. They are the name of the file (i.e. myfirstfile.txt) and Mode.
A Mode states, what you want to do with the file, once you open it. i.e. You can open a file to read it, to write something to it, to append it and create the file the first time you try opening it.
Below are the file Modes :
There are two ways by which we can create and open a file:
Let us look at the below example to create a File named myfirstfile.txt using File.new().
myfile = File.new("myfirstfile.txt", "w")
Now, if you search the above file myfirstfile.txt in the current directory. You can find an empty file myfirstfile.txt in the current folder.
So, in the above example, we have created a blank file called named myfirstfile.txt using the File.new() Method.
myfile = File.new("myfirstfile.txt", "w")
The Method, File.new() has two Arguments. First argument is the File name (i.e. myfirstfile.txt). And the second Argument is the Mode(i.e. w). Where w is the write mode.
Now, let us look at the below example to create a File named myfirstfile.txt using File.open().
File.open("myfirstfile.rb", "w") do |myfile|
Next, let us see, how can we write the above lines to the file myfirstfile.txt.