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?
source
share