December 22, 2024

Block Arguments

 

Here is an example that might help show how to use block arguments. Once a block argument(s) is declared you can use it in the block. I think that it often helps to use a meaningful word that makes it clear what you are referencing.
This code creates a dictionary of artists (strings for the keys) and their birthdays (Date objects as the corresponding values). Next, it creates a sorted collection before looping through the dictionary to find and access the keys (strings) of any 20th century artists to put them in the sorted collection. Finally it loops through the sorted collection and builds up a single string that is displayed in a dialogue box.

birthDays := Dictionary new.
birthDays
   at: 'Monet' put: (Date newDay: 14 month: #November year: 1840);
   at: 'Pollock' put: (Date newDay: 28 month: #January year: 1912);
   at: 'de Kooning' put: (Date newDay: 24 month: #April year:1904);
   at: 'Turner' put: (Date newDay: 23 month: #April year: 1775);
   at: 'Cezanne' put: (Date newDay: 19 month: #January year: 1839);
   at: 'Guston' put: (Date newDay: 27 month: #June year: 1913).

twentiethCenturyArtists := SortedCollection new.
"declare who and when as the block args"
birthDays keysAndValuesDo: [ :who :when |
    (when year between: 1900 and: 1999)
       ifTrue: [ twentiethCenturyArtists add: who ]].
artistsString := 'List of 20th century artists in alphabetic order:'.
twentiethCenturyArtists do: [ :name |
   artistsString := artistsString, '\', name ].
Dialog warn: artistsString withCRs.

You might like to note however that with keysAndValuesDo: you don't have to use both block arguments once you declare them.
You could write:

birthDays keysAndValuesDo: [ :who :when |
   (when year between: 1900 and: 1999)
     ifTrue: [ Dialog warn: 'This Date object is between 1900 and 1999']].

Not of any use, but it works.

« Back to FAQ page

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Up to top of page