Short and simple this week. When you’re writing a Ruby script you might want to know if you’re in a pipe or not. One reason might be changing how you buffer your input/output. A number of basic Unix commands do this, they act differently when piped.
I actually wrote a script where I wanted to change the command line arguments if I was in a pipe. This is probably confusing but its really useful! So there is actually an easy way to do this in Ruby:
#!/usr/bin/env ruby # Prints if the input or output is regular or piped puts "INPUT: " puts "OUTPUT: "
Proof that it works as advertised:
The documentation on IO#tty? says the following:
Returns true if [the IO stream] is associated with a terminal device (tty), false otherwise.
For those that don’t know, tty is short for teletype writer. This is an old Unix term for an interactive process that takes in user input. Nowadays it almost always means a shell/console/terminal.