Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to timeout gets.chomp

Tags:

ruby

gets

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.

like image 677
pmckinney Avatar asked Dec 10 '14 23:12

pmckinney


1 Answers

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

like image 149
fyquah95 Avatar answered Oct 12 '22 19:10

fyquah95