Add to a collection

Niko Schwarz niko.schwarz at gmx.net
Mon Feb 3 10:57:26 UTC 2003


-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Am Montag, 3. Februar 2003 01:00 schrieb Janet Abdul-Karim:

> account: aAccount
>  "Add an account to the portfolio"
>
>  self isNil ifTrue:[self add: aAccount]
>   ifFalse:[ self addLast: aAccount].

Whow, you said you put this code to a sublclass of collection. But self isNil 
is true only for one object, namely nil. But nil is of class UndefinedObject, 
so self isNil cannot be true here.

> ccounts
>  "Returns the accounts for the portfolio"
>
>  self do:[:element|^element number].

What this does is:
It wants to iterate over your elements, but then leaves the _method_ for the 
first element. Note that ^ jumps out of the method, rather than just out of 
the block.
You have two choices, either you return all those numbers as array, or you let 
the user iterate over your accounts with smth like

withAccountsDo: aBlock
  "iterate over all accounts"
  self do: [:element | aBlock value: element ]

That might be tricky to understand at first glance, so maybe returning self as 
another array is more obvious:

accounts
  ^ self collect: [ :el | el number ]

regards,

nick
- -- 
"OK, now let's look at four dimensions on the blackboard."
		-- Dr. Joy
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.1 (GNU/Linux)

iD8DBQE+PksY3P3nmXTVnC8RArRxAKDkwo+oqfluWpRouDMWSTZFSlpkHgCgmCLc
01CSCICmW4vBlDK/SSnq84M=
=MrGi
-----END PGP SIGNATURE-----



More information about the Squeak-dev mailing list