How to replace the last occurrence of a substring in ruby?

前端 未结 10 1340
南笙
南笙 2021-02-03 20:08

I want to replace the last occurrence of a substring in Ruby. What\'s the easiest way? For example, in abc123abc123, I want to replace the last abc

10条回答
  •  感动是毒
    2021-02-03 21:12

    string = "abc123abc123"
    pattern = /abc/
    replacement = "ABC"
    
    matches = string.scan(pattern).length
    index = 0
    string.gsub(pattern) do |match|
      index += 1
      index == matches ? replacement : match
    end
    #=> abc123ABC123
    

提交回复
热议问题