[Pharo-users] Loop problem on Dr Stef
henrik.s.johansen at veloxit.no
Mon Mar 31 12:14:19 EDT 2014
On 30 Mar 2014, at 1:45 , Roelof Wobben <r.wobben at home.nl> wrote:
> When I select this part:
> 1 to: 100 do:
> [:i | Transcript show: i asString; cr ].
> And do print it.
> I only see 1 where I expected to see all the numbers from 1 till 100.
> What went wrong ?
"print it" prints the return value of the expression.
In the above case, that is the return value of the to:do: method, which is the receiver, so 1 is printed.
(If you read the implementation of to:do: on Number, you’ll see there is no explicit return using ^ , in such cases the return is always the receiver)
If you wanted to print a list of 1 .. 100 (which would be printed with print it), you’d use a method which returns such a collection for example collect:;
(1 to: 100) collect: [:each | each ].
The () are needed, since there is no to:collect: method, so instead we send collect: to an interval, which we create using 1 to: 100.
-------------- next part --------------
A non-text attachment was scrubbed...
Size: 842 bytes
Desc: Message signed with OpenPGP using GPGMail
More information about the Pharo-users