What's the difference between scan and match on Ruby string

后端 未结 3 1325
北荒
北荒 2020-12-02 16:40

I am new to Ruby and has always used String.scan to search for the first occurrence of a number. It is kind of strange that the returned value is in nested arra

3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-02 17:35

    Previous answers state that scan will return every match from the string the method is called on but this is incorrect.

    Scan keeps track of an index and continues looking for subsequent matches after the last character of the previous match.

    string = 'xoxoxo'
    
    p string.scan('xo') # => ['xo' 'xo' 'xo' ]
    # so far so good but...
    
    p string.scan('xox') # => ['xox']
    # if this retured EVERY instance of 'xox' it would include a substring
    # starting at indices 0 and 2 but only one match is found
    

提交回复
热议问题