开发者

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开发者_JS百科, but wish to support both kinds of behavior.


Look at $stdin.tty?

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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜