簡體   English   中英

如何超時gets.chomp

[英]How to timeout gets.chomp

我正在嘗試編寫一個程序,要求用戶在三秒內使用gets.chomp回答問題,否則答案將自動返回false。

我想出除了超時部分以外的一切,我想知道是否有人可以請求幫助。

您可以使用timeout標准庫

require "timeout"

puts "How are you?"
begin
  Timeout::timeout 5 do
    ans = gets.chomp
  end
rescue Timeout::Error
  ans = nil
end
puts (ans || "User did not respond")

閱讀有關該庫的更多信息http://www.ruby-doc.org/stdlib-2.1.5/libdoc/timeout/rdoc/Timeout.html

你可以使用Kernel::select來編寫這樣的helper方法:

def gets_with_timeout(sec, timeout_val = nil)
  return gets.chomp if select([$stdin], nil, nil, sec)
  timeout_val
end

然后你可以像這樣使用它:

puts "How are you?"
ans = gets_with_timeout(5)
puts ans || "User did not respond"

我為此寫了一些代碼。

def question_time
  puts "Your question here"
  t = Time.now
  answer = gets.chomp
  Time.now - t > 3 ? false : answer
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM