Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby string split with terminal strings empty [duplicate]

Tags:

ruby

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?

like image 440
onezeno Avatar asked Nov 11 '13 22:11

onezeno


1 Answers

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.

like image 177
Peter Alfvin Avatar answered Oct 11 '22 13:10

Peter Alfvin