Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Ruby, how do I combine sleep with gets? I want to wait for user response for 1 min, otherwise continue

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.

like image 682
RSD Avatar asked Jun 03 '11 19:06

RSD


2 Answers

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...
}
like image 98
the Tin Man Avatar answered Nov 07 '22 08:11

the Tin Man


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?
like image 1
cam Avatar answered Nov 07 '22 08:11

cam