-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,669
  • 1
  • 19
  • 31
Zack
  • 2,207
  • 2
  • 23
  • 43

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
  • 6,304
  • 3
  • 18
  • 44
  • Did you try it? It works! Why did you vote down? I know Timeout doesn't work well in Windows for input from the console. In Ubuntu it works perfectly. I use Ruby only in Ubuntu – mechnicov Dec 17 '18 at 23:19
  • 1
    I can confirm this works. No idea why it would be downvoted. – anothermh Dec 17 '18 at 23:34
  • @Zack, I update my answer for you, I added information about `STDIN.gets` in Windows. Please try it again and cancel downvoting. – mechnicov Dec 17 '18 at 23:38
  • 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://docs.microsoft.com/en-us/windows/wsl/install-win10) to skip past all these implementation quirks and workarounds. – anothermh Dec 18 '18 at 02:37