I'm running a loop, in which I wait for a user response using the "gets.chomp" command. How can I combine that with a sleep/timer command?
For example. I want it to wait 1 min for the user to enter a word, otherwise it would continue back to the loop.
You should look at Ruby's Timeout
.
From the docs:
require 'timeout'
status = Timeout::timeout(5) {
# Something that should be interrupted if it takes too much time...
}
I think the Timeout method above is probably the most elegant way of solving this problem. Another solution that is available in most languages is using select
. You pass a list of file descriptors to monitor and an optional timeout. The code is much less concise:
ready_fds = select [ $stdin ], [], [], 10
puts ready_fds.first.first.gets unless ready_fds.nil?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With