What are all the common ways to read a file in Ruby?

dsg picture dsg · Apr 5, 2011 · Viewed 350.6k times · Source

What are all the common ways to read a file in Ruby?

For instance, here is one method:

fileObj = File.new($fileName, "r")
while (line = fileObj.gets)
  puts(line)
end
fileObj.close

I know Ruby is extremely flexible. What are the benefits/drawbacks of each approach?

Answer

mckeed picture mckeed · Apr 5, 2011

The easiest way if the file isn't too long is:

puts File.read(file_name)

Indeed, IO.read or File.read automatically close the file, so there is no need to use File.open with a block.