Date dayMonthYearDo: aBlock
"Supply integers for day, month and year to aBlock and return the result"
^ start dayMonthYearDo: aBlock
此消息的典型有效块应该是什么样的?
答案 0 :(得分:5)
在这种情况下,评论“供应整数等”意味着参数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
时,即接收方{{1} 1月1日是一个更“严肃”的方法看起来像
aDate
答案 1 :(得分:3)
这样的事情:
Date today dayMonthYearDo: [:d :m :y| Transcript cr;
show: 'today is the ';
show: d;
show: 'th'
]
today is the 28th
但当然,你可以做一些不同的事情,只是在成绩单上显示事物