Ruby stdin content detection

I want to know if anyone is trying to display the contents of the ruby ​​program on stdin. I do not want the ruby ​​to go back to allowing interactive input. How to do it?

# When called in bash like this, I want 'cat.rb' to exit immediately:
ruby cat.rb

# When called in bash like this, I want to see the word 'hello':
echo hello | ruby cat.rb

If I only cat.rbhave it puts gets, then the first example will block, waiting for EOF on the interactive stdin. I do not want to change the calling command, but I want to support both kinds of behavior.

+5
source share
1 answer

Take a look $stdin.tty?

ruby cat.rb
# $stdin.tty? -> true

echo hello | ruby cat.rb
# $stdin.tty? -> false
+5
source

All Articles