smalltalk Smalltalk Syntax Loops in Smalltalk


Example

For this example, an Ordered Collection will be used to show the different messages that can be sent to an OrderedCollection object to loop over the elements.
The code below will instantiate an empty OrderedCollection using the message new and then populate it with 4 numbers using the message add:

anOrderedCollection := OrderedCollection new.
anOrderedCollection add: 1; add: 2; add: 3; add: 4.

All of these messages will take a block as a parameter that will be evaluated for each of the elements inside the collection.

  1. do:
    This is the basic enumeration message. For example, if we want to print each element in the collection we can achieve that as such:

    anOrderedCollection do:[:each | Transcript show: each]. "Prints --> 1234"
    

    Each of the elements inside the collection will be defined as the user wishes using this syntax: :each This do: loop will print every element in the collection to the Transcript window.


  1. collect:
    The collect: message allows you to do something for each item in the collection and puts the result of your action in a new collection
    For example, if we wanted to multiply each element in our collection by 2 and add it to a new collection we can use the collect: message as such:

    evenCollection := anOrderedCollection collect:[:each | each*2]. "#(2 4 6 8)"
    

  1. select:
    The select: message allows you to create a sub-collection where items from the original collection are selected based on some condition being true for them. For example, if we wanted to create a new collection of odd numbers from our collection, we can use the select: message as such:

    oddCollection := anOrderedCollection select:[:each | each odd].
    

    Since each odd returns a Boolean, only the elements that make the Boolean return true will be added to oddCollection which will have #(1 3).


  1. reject:
    This message works opposite to select: and rejects any elements that make the Boolean return true. Or, in other words it will select any elements that make the Boolean return false. For example if we wanted to build the same oddCollection like the previous example. We can use reject: as such:

    oddCollection := anOrderedCollection reject:[:each | each even].
    

    oddCollection will again have #(1 3) as its elements.


These are the four basic enumeration techniques in Smalltalk. However, feel free to browse the Collections class for more messages that may be implemented.