Date dayMonthYearDo: aBlock
"Supply integers for day, month and year to aBlock and return the result"
^ start dayMonthYearDo: aBlock
What should a typical valid block look like for this message?
In this case the comment "Supply integers, etc." means that the argument aBlock
will receive three integers as "actual" arguments: day number, month index and year. This means that you will have to create a block with three "formal" arguments, say, day
, monthIndex
and year
as in:
aDate dayMonthYearDo: [:day :monthIndex :year | <your code here>]
The code you write inside <your code here>
can refer to the "formal" parameters day
, monthIndex
and year
, much as if it was a method with these three arguments.
This is how blocks generally work in Smalltalk.
Example
aDate
dayMonthYearDo: [:day :monthIndex :year |
monthIndex + day = 2
ifTrue: [Transcript show: 'Happy ' , year asString, '!']]
UPDATE
The example above checks for January 1st by "ingeniously" comparing monthIndex + day
with 2
. In fact, since both variables are >= 1 the only way to get 2
is when day
and monthIndex
are both 1
, i.e., when the receiver aDate
is January 1. A more "serious" approach would look like
(monthIndex = 1 and: [day = 1]) ifTrue: [ <etc> ]