Today we will cover basic file handling in Ruby. There are a few different modes for file operations listed below.
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.
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"
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!