[Newbies] How to empty a collection?
cdrick
cdrick65 at gmail.com
Tue Feb 19 15:06:50 UTC 2008
>
> aCollection copy do: [:anElement |
> aCollection remove: anElement
> ].
>
> Why copy? If you start removing items from the collection, increasing the
> index will cause you to skip elements.
I forgot that in my first attemp (and I knew that !)...
col := #(1 2 3) asOrderedCollection.
col removeAll: col.
^col returns an OrderedCollection(2)
col removeAll: col copy is ok.
So, following Bert suggestion, would it be possible to change removeAll: from...
removeAll: aCollection
aCollection do: [:each | self remove: each].
^ aCollection
to
removeAll: aCollection
aCollection copy do: [:each | self remove: each].
^ aCollection
or
removeAll: aCollection
aCollection == self
ifTrue: [aCollection copy do: [:each | self remove: each]]
ifFalse: [aCollection do: [:each | self remove: each]].
^ aCollection
or again
removeAll: aCollection
aCollection == self
ifTrue: [self removeAll: aCollection copy]
ifFalse: [aCollection do: [:each | self remove: each]].
Or maybe, if aCollection == self, a warning could be raised ?
What do you think ?
Cédrick
More information about the Beginners
mailing list