Reputation: 1077
For example these two lines which are identical other than separator return different arrays.
"1,2,,3,4,,".split(',')
=> ["1", "2", "", "3", "4"]
"1 2 3 4 ".split(' ')
=> ["1", "2", "3", "4"]
Upvotes: 1
Views: 55
Reputation: 364
Depending on what you are looking for, you can either pass in an empty string:
'1 2 3 4 '.split( '' )
# => ["1", " ", "2", " ", " ", "3", " ", "4", " ", " "]
Or use regex:
'1 2 3 4 '.split( /\s/ )
# => ["1", "2", "", "3", "4"]
Upvotes: 1
Reputation: 12412
Because a single whitespace passed to the method String#split
has special meaning.
From the docs:
If pattern is a String, then its contents are used as the delimiter when splitting str. If pattern is a single space, str is split on whitespace, with leading whitespace and runs of contiguous whitespace characters ignored.
Upvotes: 1