Today we will cover basic file handling in Ruby. There are a few different modes for file operations listed below.
File modes:
w: Write to a file. If the file doesn’t exist, it will be created. All content in the file will be erased and replaced.
r: Read a file. Will throw a fatal error if the file cannot be found/read.
a: Append text to a file. Will create file if it doesnt exist. Will never overwrite text.
Next to that, there are also different ways to open the files listed below.
Modifier:
t: Open a file in text mode. Will only work with simple text files. Default.
b: Open a file in binary mode. You can read every file using this mode, but it will not return readable text.
You can leave out the modifier and Ruby will default to text mode. Otherwise, you simply append the modifier to the mode.
Now let’s start! We write this code:
file = File.open("Textfile.txt", "w")
file.puts "Sample Textfile"
file.close
Let’s break it down!
In the first line, we open the file using File.open(filename, mode) and assign it to a variable called file.
Then we use file.puts “Sample Textfile” to weite text into the file.
Once we’re done, we close the file using file.close.
If you did everything right, a file called Textfile.txt should appear in the directory of the script. Congratulations, you just wrote text using Ruby!
Any Questions? Leave a comment or send me a message. :)
And as always, Happy Coding!
just want to add on r+, w+ and a+:
r+: will open a file for both reading and writing -- file must exist
w+: will create an empty file for both reading and writing
a+: will open file for reading and appending -- file is created if it does not exist
thanks @privateger
Thanks for your comment!
I have only just now seen it :)