Introduction To Ruby
File Handling

Reading A Text File

Start by making a text file with some lines of text inside it. To make life easier, place the file in the same folder that you intend to use for the Ruby scripts that access the file. Something like this would be fine for the example,


For this example, the text file was saved as names.txt.

# Reading a file'names.txt', 'r') do |f|
  while line=f.gets
    puts line


The 'r' in the statement is the file mode. In this case, read-only was the mode. There are several other modes, the most useful being 'r+' (reading and writing - opens from the beginning of the file), 'w' (writing - creates a new file or truncates an exisiting file) and 'a' (append - opens file for writing starting at the end of the file).

The |f| is the reference to the file within the block. The while loop reads each line of the file - notice the use of an assignment, rather than a conditional statement. When there are no more lines to be read, the loop ends.

Writing To A Text File

The following example writes the alphabet to a file, copying it from the contents of an array.

# Writing to a file

letters = ('a'..'z').to_a'alphabet.txt', 'w') do |f|
  for i in 0..26 do
    f.puts letters[i]



If you took up the challenge to make a hangman game, adding the facility to read the words from a text file would improve the script and make for a more interesting game.

Alternatively, the logic for operating a high score table is interesting to program. Use around 5 names and scores, something similar in structure to the sample file at the start of this page would work. The hard thing is to do the insertions into the score table.