[Newbies] next or break in a loop

Tobias Pape Das.Linux at gmx.de
Mon May 9 19:15:32 UTC 2016


Hi Joseph,

On 09.05.2016, at 19:51, Joseph Alotta <joseph.alotta at gmail.com> wrote:

> Greetings,
> 
> I am in need of a way to go to the end of a do loop.
> 
> myCollection do:  [ :item |
> 
>                (blah blah) ifTrue: “we found an item of the first type”
>                 next item.
> 
>                (blah blah) ifTrue: “we found an item of the second type”
>                 next item.
> 
>                (blah blah) ifTrue: “we found an item of the third type”
>                next item.
> 
>                (blah blah) ifTrue: “we found an item of the fourth type”
>                next item.
> 
>                (blah blah) ifTrue: “we found an item of the fifth type”
> 
> ].

Can you go a little into detail?
Typically, I'd put whatever is to be done when you "know of what type" your items are into its Class, 
relying on polymorphism.

For example, given you have ducks, cats, and dogs and want them to call, you'd do:

Dog>>call
  self sound: 'Waff Waff'.

Cat>>call
  self sound: 'Meow'.

Duck>>call
  self sound: 'Quak!'.


So you can use it like this:

{Dog new. Cat new. Dog new. Duck new. Duck new} do: [:animal |
  animal call].
"=> 'Waff Waff', 'Meow', 'Waff Waff', 'Quak!', 'Quak!'

What happens when you have a Centipede that does not call at all?

Well, let's assume the animals are organized all together in a common super class, Animal.

In Animal, we say

Animal>>call
  ^ self

to say a 'generic' animal does not do anything when calling.
We could do

Centipede>>call
  ^ self

or 

Centipede>>call
  ^ super call

but that superfluous given Animal>>call.

So, what do we have now?

{Dog new. Cat new. Centipede new. Dog new. Duck new. Centipede new. Duck new} do: [:animal |
  animal call].
"=> 'Waff Waff', 'Meow', 'Waff Waff', 'Quak!', 'Quak!'


That way, no 'goto' or 'continue' is necessary.

Best regards
	-Tobias





More information about the Beginners mailing list