If I define a string with nulls
string = "a,b,,c,d,e,f,,"
then
string.split(',')
=> ["a", "b", "", "c", "d", "e", "f"]
The empty string between "b" and "c" is accounted for, but the two at the end have been lost. How can I split a string and preserve those trailing empty strings in the returned array?
You need to say:
string.split(',',-1)
to avoid omitting the trailing blanks.
per Why does Ruby String#split not treat consecutive trailing delimiters as separate entities?
The second parameter is the "limit" parameter, documented at http://ruby-doc.org/core-2.0.0/String.html#method-i-split as follows:
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.
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