How to process every line in a text file with Ruby

There are quite a few ways to open a text file with Ruby and then process its contents, but this example probably shows the most concise way to do it:

# ruby sample code.
# process every line in a text file with ruby (version 1).
file='GettysburgAddress.txt'
File.readlines(file).each do |line|
  puts line
end

As you can see, this example code is very concise, and inside the processing loop you can do whatever you need to do with the line variable.

A second approach

If for some reason that approach doesn't work for you (such as having the need to have a reference to a filehandle so you can test the file before processing it), this second Ruby file-processing example can also work for you:

# ruby sample code.
# process every line in a text file with ruby (version 2).
file='GettysburgAddress.txt'
f = File.open(file, "r")
f.each_line { |line|
  puts line
}
f.close

Either approach is very readable, and lets you use Ruby to process each line of the text file, one line at a time.

Add new comment

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.