liveBook · Manning

Standard input

As explained in The Well-Grounded Rubyist, Fourth Edition

Standard input is a process's conventional input stream for receiving data from its environment.

Standard input is the conventional input stream through which a Ruby process receives data from its environment. By default, Ruby treats keyboard input as standard input, and methods such as gets read from it. STDIN is an IO object representing this stream. section 12.1.3 section 12.1.1

Read a line or character

line = STDIN.gets char = STDIN.getc gets returns one line, while getc returns one character. Both operations are buffered: terminal input normally becomes available after Enter is pressed. Using STDIN explicitly continues to read the keyboard even if $stdin has been redirected. section 12.1.4

STDIN also supports IO and Enumerable behavior:

  • Iteration normally uses the global input record separator $/; with its default newline value, each iteration reads one line. section 12.1.2
  • Changing $/ changes what counts as one input record; setting it to "NEXT" makes iteration continue until that string appears. section 12.1.2
  • Enumerable methods such as select and map can filter or transform records read from standard input. section 12.1.2
  • STDIN is a constant for the original stream, while $stdin is a reassignable global variable used to change default input behavior. section 12.1.3
>> STDIN.each {|line| p line }
This is line 1
"This is line 1\n"
This is line 2
"This is line 2\n"
All separated by $/, which is a newline character
"All separated by $/, which is a newline character\n"

Shows line-by-line STDIN iteration, including the newline retained in each yielded string. section 12.1.2

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains IO representation, line and character reads, buffering, Enumerable iteration, custom record separators, and STDIN versus $stdin.
Examples
Demonstrates line and character reads, line iteration, custom NEXT-delimited records, filtering, and mapping input records.
What it assumes
Assumes basic Ruby objects and methods while teaching IO objects, standard streams, input buffering, and Enumerable behavior.
What you can do after
Apply it via STDIN, gets, getc, and Enumerable methods to read, filter, and transform process input.
How it connects
Connects standard input to IO objects, Enumerable, gets, getc, standard output, standard error, and global I/O variables.

Also explained in

Compare how 5 books explain standard input →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.