检测Ruby中的stdin内容

时间:2011-08-18 22:27:41

标签: ruby

我想知道是否有人试图在stdin上提供ruby程序内容。我不希望ruby回退到允许交互式输入。我该怎么做?

# 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

如果我只有cat.rb包含puts gets,那么第一个示例将阻止,等待交互式标准输入上的EOF。我不想修改调用命令,但希望支持这两种行为。

1 个答案:

答案 0 :(得分:5)

查看$stdin.tty?

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

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