From: Kirk Haines Date: 2006-05-23T10:19:48+09:00 Subject: Re: How to "go to" in a RUBY script . . . On Monday 22 May 2006 6:04 pm, Louis J Scoras wrote: > Precisely what I was thinking. The spaghetti code problem is largely > attributed to non-local use of flow control. I do miss being able to > easily jump out of a nested loop, and with the labeling construct Phil > refers to I think it's pretty readable. The Ruby way involes a little more typing than the Perl way, but it seems pretty easy to me: ----- tc = 0 catch(:bailout) do while true tc += 1 throw :bailout if rand(50000) == 1 end end puts "Bailed out after #{count} iterations." ----- I like this. It's very flexible. It lets me pass data out of the dark inner place that the execution path is escaping from, and it will let me nest catch() statements if I want. Another silly, slightly more complex example: ----- def do_iterations iterations = Hash.new {|h,k| h[k] = 0} tc = 0 while true tc += 1 iterations[0] += 1 while tc % 100 != 0 tc += 1 iterations[1] += 1 while tc % 10 != 0 iterations[2] += 1 tc += 1 throw(:bailout,[tc,iterations]) if rand(50000) == 1 end end end end count,iterations = catch(:bailout) {do_iterations} puts "Bailed out after #{count} iterations.\nIterations: #{iterations.inspect}" ----- catch/throw don't need to be used often, but when they are needed, they work great for all of the same thing that labeled loops in Perl work for, and then some. Kirk Haines