I observed a strange behavior of the split
method on a String
.
"1..2".split('..') # => ['1', '2']
"1..2".split('..', 2) # => ['1', '2']
"..2".split('..') # => ['', '2']
"..2".split('..', 2) # => ['', '2']
Everything like expected, but now:
"1..".split('..') # => ['1']
"1..".split('..', 2) # => ['1', '']
I would expect the first to return the same that the second.
Does anyone have a good explanation, why "1..".split('..')
returns an array with just one element? Or is it an inconsistency in Ruby? What do you think about that?
According to the Ruby String documentation for split
:
If the limit parameter is omitted, trailing null fields are suppressed.
Regarding the limit
parameter, the Ruby documentation isn't totally complete. Here is a little more detail:
limit
is positive, split
returns at most that number of fields. The last element of the returned array is the "rest of the string", or a single null string ("") if there are fewer fields than limit
and there's a trailing delimiter in the original string.Examples:
"2_3_4_".split('_',3)
=> ["2", "3", "4_"]
"2_3_4_".split('_',4)
=> ["2", "3", "4", ""]
limit
is zero [not mentioned in the documentation], split
appears to return all of the parsed fields, and no trailing null string ("") element if there is a trailing delimiter in the original string. I.e., it behaves as if limit
were not present. (It may be implemented as a default value.)Example:
"2_3_4_".split('_',0)
=> ["2", "3", "4"]
limit
is negative, split
returns all of the parsed fields and a trailing null string element if there is a trailing delimiter in the original string.Example:
"2_3_4".split('_',-2)
=> ["2", "3", "4"]
"2_3_4".split('_',-5)
=> ["2", "3", "4"]
"2_3_4_".split('_',-2)
=> ["2", "3", "4", ""]
"2_3_4_".split('_',-5)
=> ["2", "3", "4", ""]
It would seem that something a little more useful or interesting could have been done with the negative limit
.
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