سؤال

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