How to add a user interrupt to an infinite loop?

I have a ruby ​​script below which numbers from 1 to endlessly print. How can I make a script stop infinite execution through an interrupt in the terminal, such as "Ctrl + C" or the "q" key?

a = 0 while( a ) puts a a += 1 # the code should quit if an interrupt of a character is given end 

Through each iteration, user input is not requested.

+7
source share
2 answers

I think you will need to check the exit condition in a separate thread:

 # check for exit condition Thread.new do loop do exit if gets.chomp == 'q' end end a = 0 loop do a += 1 puts a sleep 1 end 

BTW, you will need to enter q<Enter> to exit, as standard data entry does.

+4
source

Use Kernel.trap to set the signal handler for Ctrl-C:

 #!/usr/bin/ruby exit_requested = false Kernel.trap( "INT" ) { exit_requested = true } while !exit_requested print "Still running...\n" sleep 1 end print "Exit was requested by user\n" 
+13
source

All Articles