How To Read a File In Ruby
I was messing about some more today with files in Ruby today. So I want to read the contents of a file and output it to the screen.
We are going to need to open the file using the ‘open’ method from the Kernel. The ‘open’ method accepts a code block that does the actual reading. To read the contents of the file we will look at a few of the methods available from the ‘IO’ class.
I created a file called shopping.txt, and it contains the following text:
Shopping list 1. Butter 2. Milk 3. Bread 4. Cheese 5. Tomatoes
To read all the contents we are going to call the ‘read’ method.
With this code, we read all the lines of the file into a ‘string’ variable. We then go ahead and print out the class and the contents of the file.
Now let’s say you want an array of strings, an entry for each line in the file. Easy!
Instead of calling ‘read’ I called ‘readlines’ and that is it I get an array and do a happy dance. Ruby thanks for making life so awesome!