How to read the whole file in Ruby?

Is there a built-in function in Ruby to read the entire file without using any loop? So far, I have only met methods that are read in chunks (string or character).

+54
ruby file
Jul 25 2018-10-10T00:
source share
3 answers
IO.read("filename") 

or

 File.read("filename") 
+76
Jul 25 '10 at 8:11
source share
 File.readlines("filename") 

This is also a great way to read everything from a file and split the split into carriage returns. Return is an array with one row per element.

+18
Jul 25 '10 at 11:40
source share

Please ignore the advice that says: "You should never interrupt (which is an annoying term for this)." Sometimes this is a very useful and reasonable thing.

Suppose you read the file again: there is a good chance that reading the file into an array is a reasonable optimization when reading a file line by line, even though o / s will cache the file.

+5
Jan 16 '16 at 2:31 on
source share



All Articles