Search code examples
rubytimersleepgets

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.


Solution

  • 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?