Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting stdin content in Ruby

Tags:

ruby

I want to know whether or not someone is trying to give a ruby program content on stdin. I do not want ruby to fall back to allowing interactive input. How do I do this?

# 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 just have cat.rb contain puts gets then the first example will block, waiting for an EOF on interactive stdin. I don't want to modify the calling command, but wish to support both kinds of behavior.

like image 604
Peter Avatar asked Aug 18 '11 22:08

Peter


1 Answers

Look at $stdin.tty?

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

echo hello | ruby cat.rb
# $stdin.tty? -> false
like image 175
Peter Avatar answered Sep 30 '22 14:09

Peter