$stdin.gets is not working when execute ruby scrip

2019-08-30 10:39发布

Here comes a sample ruby code:

r = gets
puts r

if the script is executed standalone from console, it work fine. But if i ran it via pipeline:

echo 'testtest' | ruby test.rb

gets seem is redirected to pipeline inputs, but i need some user input.

How?

1条回答
看我几分像从前
2楼-- · 2019-08-30 11:21

Stdin has been attached to the receiving end of the pipe by the invoking shell. If you really need interactive input you have a couple choices. You can open the tty input directly, leavng stdin bound to the pipe:

tty_input = open('/dev/tty') do {|f| f.gets }

/dev/tty works under linux and OS/x, but might not work everywhere.

Alternatively, you can use a different form of redirection, process substitution, under bash to supply the (formerly piped) input as a psuedo-file passed as an argument and leave stdin bound to your terminal:

ruby test.rb <(echo 'testtest')

# test.rb
input = open(ARGV[0])
std_input = gets
input.readlines { |line| process_line(line) }
查看更多
登录 后发表回答