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

39,445

Solution 1

What about IO.read()?

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

Solution 2

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.

Share:
39,445
Dan Tao
Author by

Dan Tao

Author of the blog The Philosopher Developer and the open source libraries lazy.js and nearest-color (among others), and cohost of the podcast Spaceflix. GitHub: dtao Twitter: @dan_tao SoundCloud: dantao I’m the Head of Engineering for Bitbucket Cloud. Previously I've worked at Google, Cardpool, and ThoughtWorks.

Updated on October 12, 2021

Comments

  • Dan Tao
    Dan Tao over 2 years

    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?

  • FilBot3
    FilBot3 almost 9 years
    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
    FilBot3 almost 9 years
    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?
  • Борис Чиликин
    Борис Чиликин almost 8 years
    @Pred it loads it into a string and therefore into memory.