Sean Chittenden <sean-ruby-talk / chittenden.org> writes:

> 	Howdy.  What's the best way to prevent infinite loops in Ruby?  

Don't write one.  :)

> loop_count = 0
> while some_action
>   if loop_count > 1000
>     raise(RuntimeError, "Too many iterations of main loop")
>   else
>     loop_count += 1
>   end
> 
>   ...
> end

I guess I'd ask: what's the driver of the loop? Is it the test for
some_action, or is it the count, or both. If the count is incidental,
then I'd tuck it away inside the loop (although possibly making it
slightly shorter)

   while some_action
     raise "Too many iterations" if (loop_count += 1) > 1000

     # do the rest
   end

I might even objectify it:

   # untested

   class LoopWatch
     def initialize(max = 1000)
       @max = max
     end

     def round_we_go
       @max -= 1
       raise "Too many times..." if @max <= 0
     end
   end


   watchdog = LoopWatch.new(10000)

   while some_action
      watchdog.round_we_go

      # ...
   end

If the count is the driver of the loop (that is the count is often the
thing that terminates the loop) I'd make it part of the condition:

  while some_action and loop_count < 1000


So I guess the answer is: it depends...


Dave