Learn Ruby the Hard Way – Exercise 17 More Files

Here is my work for exercise 17.

Exercise 17 code
Exercise 17 code
I copied the file to a new file named superman.txt
I created a file called text.txt, then I ran ex17.rb and copied the file content to a new file named new_file.txt

After running ex17.rb, I used the ls command to list all the files in the directory. I could see that the new_file was in there, I then used subl to open the new_file in Sublime Text. Its content was the same sentence as the test.txt file that we copied from.

Study Drills
1. This script is really annoying. There’s no need to ask you before doing the copy, and it prints too much out to the screen. Try to make the script more friendly to use by removing features.

Shortened file copier!
Shortened file copier!

2. See how short you can make the script. I could make this one line long.
Err, 10? Maybe less lines with ; to show the end of a line of code.

3. Notice at the end of the What You Should See I used something called cat? It’s an old command that “con*cat*enates” files together, but mostly it’s just an easy way to print a file to the screen. Type man cat to read about it.
Typing man cat in the Terminal brings up the documentation. To exit less, you simply type q.

4. Find out why you had to write out_file.close in the code.
When you close a file, you ensure that all pending output is written to the file and operating system resources associated with the file handle are freed. If you open a file in write mode, forget to close it, then try to open the file in say append mode, trying to add a new sentence to the file will not work. You must first close the file, and then reopen in append mode.

This exercise I learned how to take one file’s data and copy it to a new file. This exercise takes the in_file and out_file variables from the command line through ARGV. I learned how to check if a file exists by using .exist? method on the file object (returns a boolean, true or false value). It is important to close files after you are done with them so you don’t have memory leaks and too many file pointers.


2 thoughts on “Learn Ruby the Hard Way – Exercise 17 More Files

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s