The string.split method in ruby behaves funny to me
Since your delimiter is that and Ruby can't guess that you don't need null entries. Consider your example, but replace the a
comma character .
txt = "1,,,5"
In my world, I might consider that 4 columns with zero values are implied for the middle two. I certainly wouldn't want it to delete empty entries, because if there weren't 4, I wouldn't know which ones should be zeros.
Since it cannot guess, it returns both empty "fields" and non-empty "fields" in the array. Use @ S.Mark's solution if you need to omit empty fields.
a source to share
The behavior you see makes sense. When you call string.split("a")
, you say "use" a "as a delimiter and give me an array of values between the delimiters. Between the first" a "and the second," a "in the txt
value is an empty string; the same goes for the value between the second and third" a ". That's why you see[1, "", "", 5]
As if txt were 1,,,5
and you chose ',' as separator. If someone asked what are the values in the list, it would be:
- 1
- empty
- empty
- five
a source to share
When you call split
, you are passing in a delimiter, which by its nature is removed from the string when it is split.
Take the following for example:
s = ",foo"
When you call s.split(",")
, you say, "Take everything on the left side of the comma and put your own array entry in it, then take everything on the right side of the comma and put it in the next entry, ignoring the comma itself." The function sees "everything to the left of the comma" as ""
, not as nothing.
So your line follows the following pattern:
1aaa5
1, aa5
1, '', a5
1, '', '', 5
This explains why there are two blank lines and not just [1,5]
a source to share