5

I want to know whether or not someone is trying to give a ruby program content on stdin. I do not want ruby to fall back to allowing interactive input. How do I do this?

# 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

If I just have cat.rb contain puts gets then the first example will block, waiting for an EOF on interactive stdin. I don't want to modify the calling command, but wish to support both kinds of behavior.

Peter
  • 127,331
  • 53
  • 180
  • 211

1 Answers1

5

Look at $stdin.tty?

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

echo hello | ruby cat.rb
# $stdin.tty? -> false
dpst
  • 1,283
  • 1
  • 15
  • 23
Peter
  • 127,331
  • 53
  • 180
  • 211
  • Maybe have a look at this thread: http://stackoverflow.com/questions/273262/best-practices-with-stdin-in-ruby This solution is listed there too. – Michael Kohl Aug 18 '11 at 22:33