2012-03-10 73 views
4

对原始问题进行重新验证。我需要一个以ruby运行的循环,并允许我将命令停止输入到控制台(使用gets可能),然后循环停止。Ruby循环直到出现问题

干杯 马丁

+0

你应该添加一些标签(例如untilloop),这样,如果别人有同样的问题,他们可以找到这个问题。 – Jwosty 2012-03-10 23:56:21

+0

我认为这个问题没有包含更多标签,没有什么比这里涉及的纯Ruby更好。应该避免像'loop'这样的标签。 – 2012-03-10 23:59:35

+0

嗯,好点。这些只是我头脑中的第一件事,但我不想提供真正的标签 – Jwosty 2012-03-11 00:05:06

回答

7

我想你可以使用这样的事情:

# Initialize the input queue. This is where the user-created info will be stored 
$QUEUE = [] 
def pending 
    old = $QUEUE 
    $QUEUE = [] 
    old 
end 

t = Thread.new do 
    loop do 
    # Ask the user for something 
    print "Enter info here: " 
    # Read information in 
    $QUEUE << gets.chomp 
    end 
end 

# Example code utilizing this; you can do whatever you like with the queue 
2.times do 
    sleep 5 
    # Print the list out 
    puts "\nYou entered: \n" << pending.join("\n") 
end 
+0

您也可以使用'exit'而不是'Thread.main.exit'。 – 2012-03-10 23:40:06

+0

这只会退出已启动的线程。 – Jwosty 2012-03-10 23:41:21

+3

我想你会把['Kernel#exit'](http://apidock.com/ruby/Kernel/exit)与['Thread.exit']混淆(http://apidock.com/ruby/Thread/exit/类)在这里。 'exit'只会终止完整的脚本,这似乎是合适的。第三个例子中的额外逻辑可以通过不设置变量并仅检查主循环内部的't.stop?'来实现。 – 2012-03-10 23:55:00