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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With