Here is my work for Exercise 15.
First I made a .txt file and typed the sentences in the exercise. Then, I made a Ruby file named ex15 and typed the code.
1. Above each line, write out in English what that line does.
2. If you are not sure ask someone for help or search online. Many times searching for “ruby THING” will find answers to what that THING does in Ruby. Try searching for “ruby open.”
I read about Ruby open and read. The open method takes a filename parameter, and returns a file object. The read method on a file object returns nil or a string. In our example, it returns a string containing the sentences we typed in our .txt file!
3. I used the word “commands” here, but commands are also called “functions” and “methods.” You will learn about functions and methods later in the book.
Okay! Looking forward to it.
4. Get rid of the lines 8-13 where you use gets.chomp and run the script again.
5. Use only gets.chomp and try the script that way. Why would one way of getting the filename be better than another?
I’m not sure about this one. I guess if you get the filename as a parameter for the ARGV, you can just run the script and the file will be opened. If you use gets.chomp, you have to type input to open the file. I’ll have to come back to this question later.
6. Start irb to start the Ruby shell, and use open from the prompt just like in this program. Notice how you can open files and run read on them from within irb?
First I had an error because I was not entering the filename as a string. The open method requires a string for the filename parameter.
7. Have your script also call close() on the txt and txt_again variables. It’s important to close files when you are done with them.