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


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

a = "

b = a.replace(, $ ).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: { |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.


Wow the Collections section is such a helpful overview!

We should plunder this for SC docs I think…