2

How would this be written to be on a single line?

in_file = open(from_file)
indata = in_file.read
chilledheat
  • 33
  • 1
  • 6
  • 1
    indata = File.open(from_file).read. from_file - path to file – Ilya Apr 01 '16 at 15:42
  • 2
    Some examples here: http://stackoverflow.com/questions/5545068/what-are-all-the-common-ways-to-read-a-file-in-ruby – orde Apr 01 '16 at 15:47
  • "How would this be written to be on a single line?" – Use semicolon instead of newline. Always works, you can write *any* Ruby program, no matter how complex, in one single line. – Jörg W Mittag Apr 01 '16 at 23:32

3 Answers3

8
File.read("/path/to/file")

It will read whole file content and return it as a result.

SunnyMagadan
  • 1,819
  • 14
  • 12
1

open("README.md").read

For very small file, this is acceptable.

dvxam
  • 604
  • 4
  • 12
0

To read ONE line you can use File.readline

Given:

cat file
Line 1
Line 2
Line 3
Line 4

In Ruby:

f=File.open("/tmp/file")

p f.readline 
# "Line 1\n"
dawg
  • 98,345
  • 23
  • 131
  • 206