-2

I am trying to print "Please input a value" and raise a Timeout::Error if input is not received in 2 seconds.

I thought I could do:

puts "Please input a value"
Timeout.timeout(2) do
  ans = gets
end
raise "aborted" unless ans == 'y'

When I run the script, it prints the message, and then just sits. If I enter a value after 10 seconds (for example), then it times out. It doesn't hit the timeout until after I input a value.

Kimmo Lehto
  • 5,910
  • 1
  • 23
  • 32
Zack
  • 2,377
  • 4
  • 25
  • 51

1 Answers1

0

As I understand, you want just y answer and you want to give 2 seconds for answering.

You can use begin..rescue..end construction and cycle until for y answer

require 'timeout'

puts 'Input something'

begin
  status = Timeout::timeout(2) { answer = gets.chomp.downcase until answer == 'y' }
rescue Timeout::Error
  puts 'Time is out'
end

But in Windows it's better to use STDIN.gets. You can read about this here

mechnicov
  • 12,025
  • 4
  • 33
  • 56
  • 1
    I can confirm this works. No idea why it would be downvoted. – anothermh Dec 17 '18 at 23:34
  • not sure what to tell you but I have tried this repeatedly and it flat does not work. So that is why I down voted it. – Zack Dec 17 '18 at 23:42
  • Did you try `STDIN.gets.chomp.downcase`? Did you read [this](https://bugs.ruby-lang.org/issues/6661)? – mechnicov Dec 18 '18 at 00:00
  • [On Windows](https://stackoverflow.com/q/10434188/3784008), consider wrapping the `gets` call in `Thread.new`, e.g., `Timeout.timeout(2) { Thread.new { gets.chomp.downcase }.join }`. This may work, it may not. Running Ruby on Windows is a crapshoot; if you have to use Windows, consider using [WSL](https://learn.microsoft.com/en-us/windows/wsl/install-win10) to skip past all these implementation quirks and workarounds. – anothermh Dec 18 '18 at 02:37