I need to check for the presence of STDIN input in a Ruby script, like the mysql
command can. If nothing is being directed to STDIN, then the script should not attempt to read STDIN.
How can this be done in a cross-platform way?
In Ruby, user input is made possible by the #gets method. During the executing of a Ruby program, when a line with the #gets method is read, the terminal is primed for input from the user. The input is returned as a string type after the #gets method is finished. puts "My name is #{name}!"
The $stdin is a global variable that holds a stream for the standard input. It can be used to read input from the console. reading.rb. #!/usr/bin/ruby inp = $stdin.read puts inp. In the above code, we use the read method to read input from the console.
This is something that's done in Linux a lot:
#!/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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With