How to remove an empty item from \n when converting string to array?

Hi,

How could I remove empty elements in the array in the following example?

(
a = "
t=120
<a4=c5=a5>=/e/3/2/e=p=(
"
)

b = a.replace(Char.nl, $ ).tr(Char.ret, $ ).split($ ).collect { |item| item.replace("=", " ") }

b returns -> [ , t 120, <a4 c5 a5> /e/3/2/e p (, ], and I want to automatically remove two empty elements in the conversion phase.

Currently I use the following way:

b.do { |item, index| if (item.size == 0) { b.removeAt(index) }}

However, is there a better way or method to do this?

This won’t work for what you want; for example try the input [[], []]. Modifying a collection while iterating over it is often unsafe and you should think carefully about it when you do.

b.reject(_.isEmpty). I recommend familiarizing yourself with the interfaces of Collection, SequenceableCollection, and ArrayedCollection.

1 Like

The in-place form is called removeAllSuchThat.

Ps. The collection classes are mostly from St-80 so there are lot’s of nice references, like the below, for instance.

https://wiki.squeak.org/squeak/uploads/SqueakClassesRef.html

3 Likes

Wow the Collections section is such a helpful overview!

We should plunder this for SC docs I think…