What's a reasonable way to read an entire text file as a single string?

Viewed 41820

I am sure this is an easy one; I just couldn't find the answer immediately from Google.

I know I could do this (right?):

text = ""
File.open(path).each_line do |line|
    text += line
end

# Do something with text

But that seems a bit excessive, doesn't it? Or is that the way one would do it in Ruby?

3 Answers

First result I found when searching.

I wanted to change the mode, which doesn't seem possible with IO.read, unless I'm wrong?

Anyway, you can do this:

data = File.open(path,'rb',&:read)

It's also good for when you want to use any of the other options:

https://ruby-doc.org/core/IO.html#method-c-new

Related