我正在运行一个循环,在其中我使用“gets.chomp”命令等待用户响应。如何将它与睡眠/定时器命令结合使用?
例如。我希望它等待 1 分钟让用户输入一个单词,否则它将继续返回循环。
你应该看看 Ruby 的Timeout
.
从文档:
require 'timeout'
status = Timeout::timeout(5) {
# Something that should be interrupted if it takes too much time...
}
我认为上面的 Timeout 方法可能是解决这个问题的最优雅的方法。在大多数语言中可用的另一种解决方案是使用select
. 您传递要监视的文件描述符列表和可选的超时。代码不太简洁:
ready_fds = select [ $stdin ], [], [], 10
puts ready_fds.first.first.gets unless ready_fds.nil?
怎么样:
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)
...