75

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?

Dan Tao
  • 125,917
  • 54
  • 300
  • 447
  • 1
    Caveat: Reading the file into memory, AKA slurping, has scalability issues. Ruby, along with Perl and other languages, can read a file line by line almost as fast as it can reading then splitting and looping through it. – the Tin Man Nov 19 '11 at 11:53
  • 1
    @the Tin Man: That's good advice, and I thank you for it. This question was asked a while ago, so I could be remembering it incorrectly; but I believe my intention at the time was to do some multi-line regex matching on the text of the file, so I did need the whole thing in memory (i.e., I wasn't just planning on reading it line-by-line). – Dan Tao Nov 20 '11 at 17:41

3 Answers3

197

IO.read() is what you're looking for.
File is a subclass of IO, so you may as well just use:

text = File.read(path)

Can't get more intuitive than that.

Thiago Silveira
  • 5,033
  • 4
  • 26
  • 29
  • 1
    Like my question for s.m., does IO, or File read the whole file into memory, or does it use a file pointer with SEEK to keep track of that instead of loading a big file into memory? – FilBot3 May 23 '15 at 21:23
  • 3
    @Pred it loads it into a string and therefore into memory. – Travis Reeder Jul 15 '16 at 15:32
45

What about IO.read()?

Edit: IO.read(), as an added bonus, closes the file for you.

s.m.
  • 7,895
  • 2
  • 38
  • 46
  • 1
    Does this put the entire file into memory, or does it keep a file pointer so it doesn't use all of your RAM reading a huge file? – FilBot3 May 23 '15 at 21:22
0

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

esotericpig
  • 282
  • 1
  • 3
  • 14