result := String new.
1 to: 10 do: [:n | result := result, n printString, ’ ’].
Run Code Online (Sandbox Code Playgroud)
smalltalk中的所有内容都是一个对象,对象通过消息进行交互.
我无法理解上面的代码如何理解消息:do:
如何将块从1迭代到10?怎么知道它必须多次重复阻塞?
有人可以解释引擎盖下发生的事情吗?
所有Smalltalk消息都遵循该模式<receiver> <message>..在这种情况下,接收器是1(子实例Number),消息是to:do:.
您可以浏览课程Number并查看其中的实施to:do::
to: stop do: aBlock
| nextValue |
nextValue := self.
[nextValue <= stop]
whileTrue:
[aBlock value: nextValue.
nextValue := nextValue + 1]
在你的例子中,stop是10和aBlock是[:n | result := result, n printString, ’ ’].所以实际上,它发送value:到aBlock反复.
现在,除此之外,许多Smalltalks在看到for:to:消息时会生成特殊的字节代码,但这只是一个优化.