Learn Ruby the Hard Way – Exercise 16 Reading and Writing Files

The past few exercises have been great as I feel I’m moving into more uncharted territory. After you learn about reading files, the next logical step is of course to write a file!

Here is my work for Exercise 16.

Exercise 16 code
Exercise 16 code
Running Exercise 16
Running Exercise 16

When I typed the code, I was a bit confused. (I find myself ‘commenting’ my head as I type each line in as to what is happening in the code. Doing comments in earlier exercises definitely helped build this habit!) We entered the filename as a parameter for ARGV, and then use the open method with this filename. But how could I open a file that did not exist? Would this give me an error saying no such file? Hmm, no errors occurred when I ran the file. Ok, the file must have been created somehow.

On line 10, we give the open method ‘test.txt’ as the filename parameter, and ‘w’… which I assumed was write mode. After some google search work, I found that w is not just for Ruby. Opening a file in w mode will either truncate the file to zero length or create a new file if the file does not exist. In our case, when we run the open method, a file object called ‘test.txt’ is created. When no parameters are given for open(filename), the default is to open the file in read mode.

This then made me question why we have to run the truncate method on 13? When we opened the file in ‘w’ mode, the file is already truncated. Hmm.. seems unnecessary! Then we ask the user for some input and store them in variables. Line 26-28 use the write method to write each of the three strings to the file. The target.write lines were repetitive and could be rewritten to be shorter. Finally, the file is closed.

Study Drills
1. If you do not understand this, go back through and use the comment trick to get it squared away in your mind. One simple English comment above each line will help you understand or at least let you know what you need to research more.
The comment trick is awesome! I basically walked through the code as I typed it out and explained some of my thoughts above.

2. Write a script similar to the last exercise that uses read and argv to read the file you just created.

My openex16.rb code
My openex16.rb code

I wrote a script and saved it as openex16.rb, however this script can be used to open any file. You would just enter a different file name as the first ARGV variable on the command line. I open the file in read mode, print the string returned by the read method, and then close the file.

openex16.rb In action!
openex16.rb In action!

3. There’s too much repetition in this file. Use strings, formats, and escapes to print out line1, line2, andline3 with just one target.write() command instead of six.

Rewriting the lines into one line.
Rewriting the lines into one line.

I ran ex16.rb again, knowing that this time since test.txt already exists, it would be truncated by the open method in write mode. I wanted to make sure the file was truncated and written to, so I entered different strings for line1, line2, and line3 this time. (And yes, I love Peanuts! I can’t wait until the Peanuts movie comes out this holiday.)

Rewriting the file, then opening the file and reading it.
Rewriting the file, then opening the file and reading it.

I open the file, write 3 lines about Peanuts characters and then close the file. Then I run openex16.rb and enter test.txt as the filename to open. The file is opened and read, with the content printed as a string. Success! We have rewritten our test.txt file!

4. Find out why we had to pass a 'w' as an extra parameter to open. Hint: open tries to be safe by making you explicitly say you want to write a file.
If we open the file with open(filename), without passing in an extra parameter, the file will be opened in read mode. We cannot write to the file in read mode. By passing in ‘w’ as an extra parameter, we are telling the open method that we want the file to be opened in write mode.

5. If you open the file with 'w' mode, then do you really need the target.truncate()? Read the documentation for Ruby’s open function and see if that’s true.
Aha, so this is why the truncate line is in the code… to make us look up the documentation! As I talked about earlier in this post, the truncate method is redundant here because when a file is opened in write mode, the file will be truncated if it is an existing file. If the file does not yet exist, a new file will be created.

(Someone told me that the most important part of recall when learning new things, is to take a quick minute or two and summarize what you have learned. This is something I will be doing for future exercises.)

In exercise 16, I learned how to open a file in ‘w’ write mode. This truncates the file if it exists and creates a new file if the file does not yet exist. I learned how to use the write strings to a file using the write method. There was some review on ARGV and how to open and read a file’s contents.



5 thoughts on “Learn Ruby the Hard Way – Exercise 16 Reading and Writing Files

  1. I found this post very helpful! I was totally stuck on how to build the string to use one target.write command instead of 6. I guess I need to practice my strings more! Anyway, many thanks 🙂


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s