Peter
Peter

Reputation: 132237

Detecting stdin content in 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.

Upvotes: 5

Views: 1421

Answers (1)

Peter
Peter

Reputation: 132237

Look at $stdin.tty?

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

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

Upvotes: 5

Related Questions