The string.split method in ruby ​​behaves funny to me

txt = "1aaa5"

Then

txt.split("a")

produces [1, "," ", 5] in ruby ​​1.9. Can anyone explain why? In particular, why not [1, 5]? Thanks.

+2


a source to share


6 answers


Since its division into each instance of "a"

  • 1aaa5 is divisible by 1 and aa5
  • aa5 is divisible by "" and a5
  • a5 is divisible by "" and 5

so, 1, "," ", 5



use / a + / or instead of "aaa"

irb(main):002:0> txt.split(/a+/)
=> ["1", "5"]

      

+10


a source


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.

+3


a source


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
+2


a source


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]

+2


a source


Your separator "a" is present 3 times. Try to divide by "aaa".

0


a source


If you don't specify a pattern to separate, separate it with spaces. So, among other solutions, you could do

txt = "1aaa5"
txt.gsub('a',' ').split
=>[1, 5]

      

(unless the text contains matching spaces).

0


a source







All Articles