Welcome to day 16 of the 49 Days of Ruby! 🎉
At some point, you will need to interact with files when coding. You may need to read a file as part of your application, write a new file or edit an existing one.
Working with the filesystem can seem overwhelming, but Ruby can help simplify it with its built-in library of methods to interact with files. Today we are going to explore two aspects of file operations: reading and writing.
Reading Files in Ruby
Let's say you need to take the contents of an external file from the file system and use it in your app you are building. How would you do that?
Thankfully, because Ruby strives to be as intuitive as possible, the method for reading a file is named
Here is an example:
file_contents = File.read("some_file.txt") # => "Here is the contents of our imaginary file..."
If you'd like to split up the reading of a file into the discrete actions of opening the file, reading the file, and then closing the file, you could do that to:
file = File.open("some_file.txt") file_contents = file.read # => "Here is the contents of our imaginary file..." file.close
File.read method manages those three aspects for you at once, however, there are times where you will want to disaggregate them and break them out like above.
Writing Files in Ruby
Just as there are helpful ways to read a file in Ruby, there are also helpful ways to write to files in Ruby. There are some extra parameters required because unlike reading a file, writing a file can cause unintended consequences.
When you read a file, you are not changing a file. When you write to a file, you are by definition changing it. As a result, some caution should always be considered.
First, we open the file, with an additional flag of
"w" for write access.
file = File.open("some_file.txt", "w")
Then, we can use the
#write method to begin writing to it:
file.write("Here is some additional text to add...")
Note, that this will replace the text in the file, If you wish to append to the file, you can open it with the
"a" flag instead.
That's it for today! See you tomorrow!
Come back tomorrow for the next installment of 49 Days of Ruby! You can join the conversation on Twitter with the hashtag #49daysofruby.
Top comments (0)