To create a new file, use the new method with the File class.
New accepts two arguements: the file name and the mode of the file. Acceptable modes to use in Ruby are:
r sets mode to Read only
r+ sets mode to Read/Write only
w sets mode to Write only
w+ sets mode to Write/Read only
a sets mode to Write only with pointer positioned at EoF
a+ sets mode to Read/Write only with pointer positioned at EoF
To open a file you have already created, use the open method with the File class
myfile = File.open("foobar.txt")
You can use the above line of code with the methods listed above as well:
myfile = File.open("foobar.txt", "w+")
Adding the w+ at the end will open this file in Read/Write Only.
Writing and Reading to Files
Make sure you have the file you wish to edit opened. You can check this with the closed? method:
This should return false if the file has been opened.
To write a line to your file, use the puts method with the File class:
myfile.puts("This is the first line in my new file")
Running this code again will add the next bit of text to a new line.
myfile.puts("This is the second line in my new file")
To read the file, you need to move the pointer back to the beginning of the file. To do this, use rewind:
Now that we are at the top of the file, we can read individual lines with:
or print the whole document to screen using the each method:
myfile.each (|line| print line)
Closing, Renaming, and Deleting Files
Once your done manipulating the file, you may want to close it.
Renaming the file is just as easy:
And when you're tired of the file all together, just delete it with: