Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby scan/gets until EOF [closed]

Tags:

ruby

eof

I want to scan unknown number of lines till all the lines are scanned. How do I do that in ruby?

For ex:

put returns between paragraphs

for linebreak add 2 spaces at end

_italic_ or **bold**  

The input is not from a 'file' but through the STDIN.

like image 388
mrudult Avatar asked Feb 08 '14 16:02

mrudult


People also ask

Does scanf return EOF?

scanf returns EOF if end of file (or an input error) occurs before any values are stored. If any values are stored, it returns the number of items stored; that is, it returns the number of times a value is assigned by one of the scanf argument pointers.

What is EOF in Ruby?

Raised by some IO operations when reaching the end of file. Many IO methods exist in two forms, one that returns nil when the end of file is reached, the other raises EOFError . EOFError is a subclass of IOError .

What is stdin Ruby?

The $stdin is a global variable that holds a stream for the standard input. It can be used to read input from the console. reading.rb. #!/usr/bin/ruby inp = $stdin.read puts inp. In the above code, we use the read method to read input from the console.


2 Answers

Many ways to do that in ruby. Most usually, you're gonna wanna process one line at a time, which you can do, for example, with

while line=gets
end

or

STDIN.each_line do |line|
end

or by running ruby with the -n switch, for example, which implies one of the above loops (line is being saved into $_ in each iteration, and you can addBEGIN{}, and END{}, just like in awk—this is really good for one-liners).

I wouldn't do STDIN.read, though, as that will read the whole file into memory at once (which may be bad, if the file is really big.)

like image 87
PSkocik Avatar answered Sep 29 '22 20:09

PSkocik


Use IO#read (without length argument, it reads until EOF)

lines = STDIN.read

or use gets with nil as argument:

lines = gets(nil)

To denote EOF, type Ctrl + D (Unix) or Ctrl + Z (Windows).

like image 32
falsetru Avatar answered Sep 29 '22 20:09

falsetru