简体   繁体   中英

How to timeout gets.chomp

I am trying to write a program that will ask the user to answer a question using gets.chomp in three seconds or the answer will automatically return false.

I figured out everything except for the timeout part and I was wondering if anyone could please help.

You can use the timeout standard library

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")

Read more about the library http://www.ruby-doc.org/stdlib-2.1.5/libdoc/timeout/rdoc/Timeout.html

You can use Kernel::select to write helper method like this:

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

Then you can use it like this:

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

I wrote some code for this.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM