在Ruby中检测标准输入内容

5

我想知道是否有人试图在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,那么第一个示例会阻塞,等待交互式stdin上的EOF。我不想修改调用命令,但希望支持两种行为。
1个回答

5

Look at $stdin.tty?

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

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

也许可以看一下这个帖子:https://dev59.com/GnVC5IYBdhLWcg3wfxU8 这个解决方案也在那里列出。 - Michael Kohl

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接