What are all the common ways to read a file in Ruby?
File.open("my/file/path", "r") do |f| f.each_line do |line| puts line endend# File is closed automatically at end of block
It is also possible to explicitly close file after as above (pass a block to open
closes it for you):
f = File.open("my/file/path", "r")f.each_line do |line| puts lineendf.close
Be wary of "slurping" files. That's when you read the entire file into memory at once.
The problem is that it doesn't scale well. You could be developing code with a reasonably sized file, then put it into production and suddenly find you're trying to read files measuring in gigabytes, and your host is freezing up as it tries to read and allocate memory.
Line-by-line I/O is very fast, and almost always as effective as slurping. It's surprisingly fast actually.
I like to use:
IO.foreach("testfile") {|x| print "GOT ", x }
or
File.foreach('testfile') {|x| print "GOT", x }
File inherits from IO, and foreach
is in IO, so you can use either.
I have some benchmarks showing the impact of trying to read big files via read
vs. line-by-line I/O at "Why is "slurping" a file not a good practice?".