Morton Goldberg
9/22/2007 12:56:00 AM
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.
<code>
trap('INT') { puts "done"; throw :quit }
count = 0
catch :quit do
while count < 10;
puts count += 1
sleep 1
end
end
</code>
Regards, Morton