In Ruby, how do I combine sleep with get? I want to wait for the user's response within 1 minute, otherwise continue

I start a loop in which I wait for the user to respond using the "gets.chomp" command. How can I combine this with the sleep / timer command?

For instance. I want him to wait 1 minute so that the user can enter a word, otherwise he will continue to return to the loop.

+5
source share
3 answers

I think the Timeout method above is probably the most elegant way to solve this problem. Another solution, available in most languages, uses select. You pass a list of file descriptors for monitoring and an additional timeout. The code is much less concise:

ready_fds = select [ $stdin ], [], [], 10
puts ready_fds.first.first.gets unless ready_fds.nil?
+1
source

You should look at Ruby Timeout.

From the docs:

require 'timeout'
status = Timeout::timeout(5) {
  # Something that should be interrupted if it takes too much time...
}
+5
source

What about:

def gets_or_timeout(to)
 # Use thread and time limit to wait for a key or refresh after time if no key is hit.
 t=Thread.new{ print "\n> "; gets}
 t.join(to) #wait for end or number of seconds
 t.kill
end

...
gets_or_timeout(60)
...
0
source

All Articles