pmckinney
pmckinney

Reputation: 63

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.

Upvotes: 6

Views: 1566

Answers (3)

TeWu
TeWu

Reputation: 6564

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"

Upvotes: 0

fyquah95
fyquah95

Reputation: 828

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

Upvotes: 11

Darkmouse
Darkmouse

Reputation: 1939

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

Upvotes: -7

Related Questions