From: Morton Goldberg Date: 2007-09-22T09:55:46+09:00 Subject: Re: Break loop by trapping INT On Sep 21, 2007, at 7:04 PM, Todd A. Jacobs wrote: > I'm trying to break a loop whenever CTRL-C is pressed, and find that > this doesn't work: > > trap 'INT', proc {break}; count=0; while count < 10; > puts count += 1; sleep 1; end > > I'm guessing it's because the loop is somehow out of scope, but I'm > not > sure why. > > Some minor syntax changes to trap makes it work, sort of. If I use: > > trap('INT') {break} > > instead, then I get a LocalJumpError. So, why does the syntax only > work > one way, and what is the right way to trap the interrupt? When the trap is triggered, the trap's proc object receives a 'call' message. This happens in the scope of top level, not in the scope of the while block. To get the result you want, you need to invoke a non- local jump mechanism. This can be done with catch and throw. trap('INT') { puts "done"; throw :quit } count = 0 catch :quit do while count < 10; puts count += 1 sleep 1 end end Regards, Morton