Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you check for STDIN input in a Ruby script?

Tags:

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?

like image 216
dan Avatar asked Jan 07 '11 02:01

dan


People also ask

How do I get input in Ruby?

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}!"

What is Stdin Ruby?

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.


1 Answers

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
like image 97
the Tin Man Avatar answered Oct 13 '22 03:10

the Tin Man