Forum: Ruby How to stop nested catch from looking messy?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Greg H. (Guest)
on 2007-01-25 19:50
(Received via mailing list)
I'm writing a parser generator (for fun) and am making use of
throw/catch to allow notification of special parse events to "bubble
up" through many levels. The trouble is that the code starts to look
ugly when I have to nest various catch blocks so as to catch three
different possible types of throw.

Check out the following loop where I am iterating over a collection of
"parseable" objects, catching and counting the different types of
throws. The "parseable" object could be something as simple as a String
or a complex hierarchy of parslets and parslet combinations; the main
point here is that I don't know what it is nor what type of throw it
might do, I only know that it should respond to the "parse" message:

alternatives.each do |parseable|
  catch(:ProcessNextAlternative) do
    catch(:NotPredicateSuccess) do
      catch(:AndPredicateSuccess) do
        catch(:ZeroWidthParseSuccess) do
          accumulate_result(parseable.parse)
          match_count     += 1
          throw :ProcessNextAlternative
        end
        zero_width_count  += 1
        throw :ProcessNextAlternative
      end
      and_predicate_count += 1
      throw :ProcessNextAlternative
    end
    not_predicate_count   += 1
  end
end

Does this design stink? Is there a better/cleaner way?

Cheers,
Greg
This topic is locked and can not be replied to.