[Newbies] break out of do

Randal L. Schwartz merlyn at stonehenge.com
Fri Oct 3 14:25:03 UTC 2008


>>>>> "Mark" == Mark Volkmann <mark at ociweb.com> writes:

Mark> Is there a way to break out of a do:? For example, if I use do: to
Mark> iterate through the characters in a string and I find a character I
Mark> don't want to allow, can I break out and avoid examining the remaining
Mark> characters?

The simplest way is to factor your code such that when you are done processing
in your loop, you answer from the method when you've reached that.

    contains: anItem

    self do: [:each|
      "some stuff here if you want"
      anItem = each ifTrue: [^true]. "breaks the loop, returns true to caller"
      "some more stuff here if you want"
    ].
    ^false "default answer if not found"
  
I'd suggest trying to get your code shaped like that.  It'll be the
most familar.

There are more complicated ways to do it with exceptions if you need
to stay within the same method.  Don't do that. :)

-- 
Randal L. Schwartz - Stonehenge Consulting Services, Inc. - +1 503 777 0095
<merlyn at stonehenge.com> <URL:http://www.stonehenge.com/merlyn/>
Smalltalk/Perl/Unix consulting, Technical writing, Comedy, etc. etc.
See http://methodsandmessages.vox.com/ for Smalltalk and Seaside discussion


More information about the Beginners mailing list