How To Read a File In Ruby

September 10, 2014

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!


Discussion, links, and tweets

My name is Deon Heyns and I am a developer learning things and documenting them in realtime. Python, Ruby, Scala, .NET, and Groovy are all languages I have written code in. I appeared in the New York Post once. I host my code up at GitHub and Bitbucket so have a look at my code, fork it and send those pull requests.

comments powered by Disqus