Zero-length string being returned from String#split

前端 未结 2 438

In Ruby 1.9.3 (and probably earlier versions, not sure), I\'m trying to figure out why Ruby\'s String#split method is giving me certain results. The results I\'m getting se

相关标签:
2条回答
  • 2020-12-21 01:24
    "abcabc".split("b") #=> ["a", "ca", "c"]
    "abcabc".split("a") #=> ["", "bc", "bc"]
    "abcabc".split("c") #=> ["ab", "ab"]
    

    Suppose you were splitting on a comma. What behaviour would you expect from ",bc,bc".split(',')? It's not different with splitting on 'a'. For the third example, split omits the trailing empties by default.

    0 讨论(0)
  • 2020-12-21 01:25

    The ruby 1.9 documentation says

    If the limit parameter is omitted, trailing null fields are suppressed.

    So if we take your example:

     "abcabc".split("a") #=> ["bc", "bc"]
    

    And we include a limit value:

     "abcabc".split("a", -1)  #=> ["ab", "ab", ""]
    

    You get the expected behavior.

    0 讨论(0)
提交回复
热议问题