Get index of string scan results in ruby

前端 未结 4 1131
半阙折子戏
半阙折子戏 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:48

    Try this:

    res = []
    "abab".scan(/a/) do |c|
      res << [c, $~.offset(0)[0]]
    end
    
    res.inspect # => [["a", 0], ["a", 2]]
    

提交回复
热议问题