The Rubyist Historian: Working With Advanced Data

In this section, a whole new world of programing is about to open before your eyes. So far, we’ve been working with simple data inputs through the use of .gets(), but the method only allows us to call upon a single data entry. What would be infinitely more useful would be the ability to read files outside the program. We can do this with Ruby’s File class.


When working with files, you have some options about how you want to access them. These are called mode specifiers and describes read/write characteristics of the file: r+ (read/write text, or append data), r (read only), w (write only), and w+ (read/write, but destructive because it destroys whatever existed in the file previously).

Imagine we have a primary source document we would like to read. You can download this file from Github to your local disk for something to work with (this is a letter from a Civil War soldier). We’re going to ask Ruby to read the file and print the results to the screen:"letter.txt", "r") do |file|
    lines = file.readlines
    puts lines

We could also print out specific lines of the array:"letter.txt", "r") do |file|  # open the file and assign to variable 'file'
    line_array = file.readlines

    puts line_array[3]
    puts line_array[5]
    puts line_array[9]

# Since we used the "r" specifier, Ruby will automatically close the
# file.  Otherwise, you will need to exit the file using file.close().

The program will print the specified lines to the screen.

We can also write to files using

file ="my_file.txt", "w")

file.write("Hello, world!")
file.write("I'm learning Ruby!")


After running the program. it will will create the file my_file in the directory you are working in. The file should contain the contents we wrote.

You now know how to read and write files. A whole new world of programming should be opening before you.

Additional Resources

Visit the Rubyist Historian Table of Contents for more sections, and check out the Github repository for an archive of all the code examples.

See something that’s wrong? Examples that don’t work? Explanations that are unclear or confusing? Embarrassing typographic errors? Drop me an email at jason.heppler+feedback at gmail and I’ll fix things right up!

Topic structure, examples, and explanations for the Rubyist Historian are inspired by, credited to, and drawn from Stephen Ramsay and his course Electronic Text.

07 January 2011 · @jaheppler