Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting into empty substrings

Tags:

string

split

ruby

I get this result (notice that the first "" is for the preceding empty match):

"babab".split("b")
# => ["", "a", "a"]

By replacing "a" with an empty string in the input above as follows,

"bbb".split("b")

I expected to get the following result:

["", "", ""]

But in reality, I get:

[]

What is the logic behind this?

like image 265
sawa Avatar asked Jan 27 '23 20:01

sawa


1 Answers

Logic is described in the documentation:

If the limit parameter is omitted, trailing null fields are suppressed.

Trailing empty fields are removed, but not leading ones.


If, by any chance, what you were asking is "yeah, but where's the logic in that?", then imagine we're parsing some CSV.

fname,sname,id,email,status
,,1,[email protected],

We want the first two position to remain empty (rather than be removed and have fname become 1 and sname - [email protected]).

We care less about trailing empty fields. Removed or kept, they don't shift data.

like image 144
Sergio Tulentsev Avatar answered Feb 02 '23 08:02

Sergio Tulentsev