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

前端 未结 10 1181
南笙
南笙 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:11

    I've used this handy helper method quite a bit:

    def gsub_last(str, source, target)
      return str unless str.include?(source)
      top, middle, bottom = str.rpartition(source)
      "#{top}#{target}#{bottom}"
    end
    

    If you want to make it more Rails-y, extend it on the String class itself:

    class String
      def gsub_last(source, target)
        return self unless self.include?(source)
        top, middle, bottom = self.rpartition(source)
        "#{top}#{target}#{bottom}"
      end
    end
    

    Then you can just call it directly on any String instance, eg "fooBAR123BAR".gsub_last("BAR", "FOO") == "fooBAR123FOO"

提交回复
热议问题