Date dayMonthYearDo: aBlock
"Supply integers for day, month and year to aBlock and return the result"
^ start dayMonthYearDo: aBlock
此消息的典型有效块应是什么样子?
在这种情况下,注释"提供整数等"意味着参数aBlock
将接收三个整数作为"实际"参数:日数、月份索引和年份。这意味着您必须创建一个包含三个"正式"参数的块,例如,day
、monthIndex
和year
,如下所示:
aDate dayMonthYearDo: [:day :monthIndex :year | <your code here>]
你在<your code here>
里面编写的代码可以引用"形式"参数day
、monthIndex
和year
,就好像它是一个带有这三个参数的方法一样。
这就是块在Smalltalk中通常的工作方式。
例
aDate
dayMonthYearDo: [:day :monthIndex :year |
monthIndex + day = 2
ifTrue: [Transcript show: 'Happy ' , year asString, '!']]
更新
上面的例子通过"巧妙地"将monthIndex + day
与2
进行比较来检查 1 月 1 日。事实上,由于两个变量都是>= 1,因此获得2
的唯一方法是当day
和monthIndex
都是1
时,即当接收方aDate
是1月1日时。一个更"严肃"的方法看起来像
(monthIndex = 1 and: [day = 1]) ifTrue: [ <etc> ]
像这样:
Date today dayMonthYearDo: [:d :m :y| Transcript cr;
show: 'today is the ';
show: d;
show: 'th'
]
today is the 28th
但是,当然,您可能会做不同的事情,只是在成绩单上显示内容