How to open a file and read its contents using Ruby

Ruby file FAQ: How do I open and read from a file in Ruby?

How many ways are there to open a file with Ruby and process the file contents? I don't know for sure, but here are two different ways to do it.

Ruby file processing, version 1

First, I'll use Ruby and the method to open a file and process its contents, like this:

# ruby file processing, version 1
f =, "r")
f.each_line { |line|
  puts line

Ruby file processing, version 2

Second, if all you need to do is open a file and process its contents one line at a time, using the File.readlines method is even more concise, as shown in this example:

# ruby file processing, version 2
File.readlines(file).each do |line|
  puts line

Wow, there are days like today where the concise syntax and readability of the Ruby language never cease to amaze me.