method that accepts a block and the block accepts an argument

淺唱寂寞╮ 提交于 2020-01-25 15:50:57

问题


How can I send a block and its argument to a method ? so the method receive the block and the block receives the argument and I run the block in the method iteslf...


回答1:


Just pass the block and its argument to the method as separate arguments. Then send #value: to the block to pass the argument to the block. E.g.

methodTaking: aBlock and: anArgument
  aBlock value: anArgument.
  ...



回答2:


For an example have a look at the sort: method of OrderedCollection (you'll find the block evaluated finally in SortedCollection>>mergeFirst:middle:last:into:by:).
Inside a method that accepts a block as parameter, you would evaluate the block, this means call it with parameters and use the result. Not so much try to "access the argument of the block".

You would e.g. send a message with a block as parameter to a collection of colors to sort it by luminance:

colors := OrderedCollection new. 
colors addAll: { Color red. Color yellow. Color white. Color black }. 
colors sort: [:c1 :c2 | c1 luminance <= c2 luminance].

results in: "an OrderedCollection(Color black Color red Color yellow Color white)"



来源:https://stackoverflow.com/questions/26889234/method-that-accepts-a-block-and-the-block-accepts-an-argument

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!