How can I add a user interrupt to an infinite loop?
问题 I have a ruby script below which infinitely prints numbers from 1 onward. How can I make the script stop its infinite execution through an interrupt in the terminal like 'Ctrl+C' or key 'q'? a = 0 while( a ) puts a a += 1 # the code should quit if an interrupt of a character is given end Through every iteration, no user input should be asked. 回答1: I think you will have to check the exit condition in a separate thread: # check for exit condition Thread.new do loop do exit if gets.chomp == 'q'