如何在Ruby脚本中检查STDIN输入?

dan*_*dan 20 ruby

我需要在Ruby脚本中检查是否存在STDIN输入,就像mysql命令一样.如果没有任何内容指向STDIN,则脚本不应尝试读取STDIN.

如何以跨平台的方式完成?

the*_*Man 31

这在Linux中做了很多事情:

#!/usr/bin/env ruby

str = (STDIN.tty?) ? 'not reading from stdin' : $stdin.read
puts str

>> $ ruby test.rb 
>> not reading from stdin
>> $ echo "reading from stdin" | ruby test.rb 
>> reading from stdin
Run Code Online (Sandbox Code Playgroud)

  • 使用“STDIN”和“$stdin”有什么具体原因吗? (2认同)