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


Ruby Problem Overview

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

# Do something with text

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

Ruby Solutions

Solution 1 - Ruby

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.

Solution 2 - Ruby

What about IO.read()?

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

Solution 3 - Ruby

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:



All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDan TaoView Question on Stackoverflow
Solution 1 - RubyThiago SilveiraView Answer on Stackoverflow
Solution 2 - Rubys.m.View Answer on Stackoverflow
Solution 3 - RubyesotericpigView Answer on Stackoverflow