Redirecting Input from Other Processes

Standard input can be used to read text from the keyboard. You might have used it that way when learning Ruby, prompting users for input and storing the text they typed:

 
print ​"What's your name? "
 
name = $stdin.gets.chomp
 
puts ​"Hi, ​​#{​name​}​​!"

Here we ask standard input—$stdin—for a line of input using the gets method, using chomp to remove the trailing newline. This gives us a string, which we store in name.

This simplistic use of standard input isn’t particularly useful, let’s face it. But it’s actually only half of the story. Standard input isn’t just used to read from the keyboard interactively; it can also read from input that’s been redirected—or piped—to your script from another process. ...

Get Text Processing with Ruby now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.