By Alvin Alexander. Last updated: June 4, 2016
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 File.open
method to open a file and process its contents, like this:
# ruby file processing, version 1 file='GettysburgAddress.txt' f = File.open(file, "r") f.each_line { |line| puts line } f.close
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='GettysburgAddress.txt' File.readlines(file).each do |line| puts line end
Wow, there are days like today where the concise syntax and readability of the Ruby language never cease to amaze me.