Shubham
Shubham

Reputation: 22307

How to read whole file in Ruby?

Is there an in-built function in Ruby to read the whole file without using any loop? So far, I have only come across methods that read in chunks (line or character).

Upvotes: 71

Views: 49148

Answers (3)

Graham Nicholls
Graham Nicholls

Reputation: 561

Please ignore advice which states "You should never slurp (which is the annoying term for this) a file". Sometimes this is a very useful, and sensible thing to do.

Suppose you're reading a file repeatedly : good chance that reading the file into an array is a sensible optimisation over reading the file line by line, even taking into account that the o/s will cache the file.

Upvotes: 5

sluukkonen
sluukkonen

Reputation: 2616

IO.read("filename")

or

File.read("filename")

Upvotes: 107

Nick
Nick

Reputation: 2413

File.readlines("filename")

This is also a great method to read everything from a file and break split on carriage returns. The return is an Array with one line per element.

Upvotes: 21

Related Questions