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:
- If
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", ""]
- If
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"]
- If
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
.