[Newbies] How to empty a collection?
Ron Teitelbaum
Ron at USMedRec.com
Tue Feb 19 15:20:55 UTC 2008
Hi Cédrick,
I believe there is too little agreement to do very much. The suggestion you
presented as Bert's suggestion was actually mine. So given the discussion
that followed I think I would actually follow Bert's advice.
aColl removeAllSuchThat: [:anElement| true].
But I suppose that is still following my own advice because
removeAllSuchThat: aBlock
"Evaluate aBlock for each element and remove all that elements from
the receiver for that aBlock evaluates to true. Use a copy to
enumerate
collections whose order changes when an element is removed (i.e.
Sets)."
self copy do: [:each | (aBlock value: each) ifTrue: [self remove:
each]]
:)
Ron Teitelbaum
> -----Original Message-----
> From: cdrick [mailto:cdrick65 at gmail.com]>
> >
> > 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