Question

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.

Was it helpful?

Solution 2

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).

OTHER TIPS

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.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top