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?
return last n lines from your_file.log or .txt
The easiest way if the file isn't too long is:
Indeed,
IO.read
orFile.read
automatically close the file, so there is no need to useFile.open
with a block.You can read the file all at once:
When the file is large, or may be large, it is usually better to process it line-by-line:
Sometimes you want access to the file handle though or control the reads yourself:
In case of binary files, you may specify a nil-separator and a block size, like so:
Finally you can do it without a block, for example when processing multiple files simultaneously. In that case the file must be explicitly closed (improved as per comment of @antinome):
References: File API and the IO API.
It is also possible to explicitly close file after as above (pass a block to
open
closes it for you):http://www.ruby-doc.org/core-1.9.3/IO.html#method-c-read
I think this method is the most "uncommon" one. Maybe it is kind of tricky, but it works if
cat
is installed.