本文介绍了如何将用户中断添加到无限循环中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ruby脚本,在它下面可以无限​​打印从1开始的数字.如何通过终端中的"Ctrl + C"或键"q"之类的中断使脚本停止无限执行?

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.

推荐答案

我认为您必须在单独的线程中检查退出条件:

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'
  end
end

a = 0
loop do
  a += 1
  puts a
  sleep 1
end

顺便说一句,您必须输入q<Enter>退出,因为这就是标准输入的工作方式.

BTW, you will have to enter q<Enter> to exit, as that's how standard input works.

这篇关于如何将用户中断添加到无限循环中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-08 07:10