How to get.chomp timeout

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

I understood everything except the timeout, and I was wondering if anyone could help.

+5
source share
3 answers

You can use the standard timeout 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") 

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

+8
source

You can use Kernel::select to write a helper method as follows:

 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" 
0
source

I wrote code for this.

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

Source: https://habr.com/ru/post/1208769/


All Articles