Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Empty strings at the beginning and end of split [duplicate]

Possible Duplicate:
Split problem in Ruby

In Ruby, when I split a string with a delimiter that matches the beginning of the string, it gives an empty string in the initial position of the array:

"abc".split(/a/) # => ["", "bc"]

but when I do a similar thing with a delimiter that matches the end of the string, it does not give an empty string:

"abc".split(/c/) # => ["ab"]

This looks inconsistent to me. Is there any rationale for such specification?

Edit If it is to be compatible with Perl's specification as in muu is to short's answer, then the question remains the same: Why is it like that in Perl? And for this reason, now it also becomes a question about Perl.

like image 785
sawa Avatar asked Nov 07 '12 15:11

sawa


1 Answers

From the fine manual:

split(pattern=$;, [limit]) → anArray
[...]
If the limit parameter is omitted, trailing null fields are suppressed. If limit is a positive number, at most that number of fields will be returned (if limit is 1, the entire string is returned as the only entry in an array). If negative, there is no limit to the number of fields returned, and trailing null fields are not suppressed.

So trailing "null fields" are suppressed because the documentation says they are. If you want the trailing empty string, ask for it:

'abc'.split(/c/, -1) # [ 'ab', '' ]

Why would it behave that way? Probably because it matches Perl's split behavior:

If LIMIT is negative, it is treated as if it were instead arbitrarily large; as many fields as possible are produced.

and we see that using a negative limit, again, gives us the trailing empty string:

$ perl -e 'print join(",", split(/c/, "abc")), "\n"'
ab
$ perl -e 'print join(",", split(/c/, "abc", -1)), "\n"'
ab,

Why copy Perl's behavior? Ask Matz.

like image 136
mu is too short Avatar answered Oct 19 '22 18:10

mu is too short