문제

What I'm trying to do is use the gets feature of ruby.

should_i_wait = gets

However I don't want to stop the program for eternity if the user doesn't enter anything. I want the boolean variable to be set to true if after 2 seconds the user didn't enter anything. Is there a simple way to do this? Is there a lovely gem out there ?

도움이 되었습니까?

해결책

You can use Timeout to achieve this:

require 'timeout'
begin
  should_i_wait = Timeout::timeout(2) do
    gets
  end
rescue Timeout::Error
  should_i_wait = true
end
puts should_i_wait
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top