Get index of string scan results in ruby

前端 未结 4 1193
半阙折子戏
半阙折子戏 2020-12-10 03:13

I want to get the index as well as the results of a scan

\"abab\".scan(/a/)

I would like to have not only

=> [\"a\", \"a         


        
4条回答
  •  鱼传尺愫
    2020-12-10 03:32

    It surprised me that there isn't any method similar to String#scan which would return array of MatchData objects, similar to String#match. So, if you like monkey-patching, you can combine this with Todd's solution (Enumerator is introduced in 1.9):

    class Regexp
      def scan str
        Enumerator.new do |y|
          str.scan(self) do
            y << Regexp.last_match
          end
        end
      end
    end
    #=> nil
    /a/.scan('abab').map{|m| m.offset(0)[0]}
    #=> [0, 2]
    

提交回复
热议问题